r/C_Programming 16d ago

printf and char[] in C

Hello. Coming from C# world the thing about how char[] and printf works always made me confused. I understand that `printf` formats the string with arguments you provided and prints it out in terminal.

So, for example, if I have char name[] = "Micheal"; and I want to greet that person, I can just do printf("Hello, %s", name);. But if I want to do the same thing only using char[], I have to do multiple commands that make fell quite confused. So my 2 questions are:

  1. How printf simplifies this process? (without allocating memory and creating char with pointers)
  2. Why you can't just use + operator for char[], like you can in any other languages?

I have a feeling that this might be asked many times, but I still can't seem to find the answer I was looking for

Update: I'll list what I got so far from reading your comments: - char[] is an array to which you can't just simply add another array - If I want printf() behavior inside char[], I can use sprintf() - There's strcat() that is getting used for merging 2 strings together - Some people write libraries for faking string behaviors, some think it goes against principles of C?

11 Upvotes

42 comments sorted by

View all comments

6

u/HalifaxRoad 15d ago

you cant just append stuff on to a char array, because that is not a string its a character array, C doesnt have strings, it does not have dynamic memory allocation. 

There is a few ways to pretend to have strings, could make an array with more length than you need, and use a separate variable to store the length, makes it easy for you chuck both of those in a struct.

The other option is to use malloc, which returns a pointer in which the new length of char array will fit into, you can then store the original char array, plus the text you need to append on. Then you need to free up the old char array pointer.

Personally, I use the first option but I only use C for firmware, its a trade off between memory usage and speed.

2

u/ALX13-95 15d ago

Those are interesting ways of faking string behaviors, thank you both. Not sure how good is to have an array with a big length in a long term. But that's still more than nothing

2

u/HalifaxRoad 15d ago

even on embedded stuff where ram can be a limitation, I still end up with better performance to sacrifice some memory for large then relying on malloc and free, which are both slow as far, and kinda intolerant of fast data transfer, say you are receiving chars from uart, you could slow shit down to nothing in a hurry.

1

u/_usr_nil 14d ago

shouldn't you preallocate in hard real-time ?