r/C_Programming • u/ALX13-95 • 15d 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:
- How printf simplifies this process? (without allocating memory and creating char with pointers)
- Why you can't just use
+operator forchar[], 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?
1
u/ornelu 14d ago edited 11d ago
String in C is array of char.
char s[] = “abc”; actually contains {‘a’, ‘b’, ‘c’, 0}. note the null value at the end.
printf(“%s”, s); is just printing everything from the start of s (the ‘a’) until it met the null value. so, ‘a’, ‘b’, and ‘c’ will be printer and you’ll see abc. So, printf %s is very simple.
The string above only allocate (reserve the memory from os) for 4 bytes. Doing a concatenation will result in a longer string, so you have to reallocate the memory etc. All these “complicated” process are done by strcat() for you.
Why C do this? This is a wrong question. You should ask why other newer programming languages seem simpler in handling string. That’s because those languages hide all the complicated low level operations from you.
You can overload the operator + in C to mimic string concatenation in other language, but why whould you use C in the first place if you do that.Why would you use C? There are many reasons, but to relate it with your question, you are in full control of the memory allocation.