r/C_Programming • u/ALX13-95 • Jul 22 '26
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 insidechar[], I can usesprintf() - 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?
23
u/Classic-Rate-5104 Jul 22 '26
Printf doesn't simplify anything. When doing %s printf just gets a char* from the stack and prints the chars it points to (up to the terminating nul-character). An operator + isn't possible in C because this operator only works on basic numeric types. A string isn't a basic type in C, it is just a array of chars which is by convention terminated by the nul-char.
5
u/HalifaxRoad Jul 22 '26
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.
3
u/zhivago Jul 22 '26
The simple answer is that C has no string type.
However, see strcat().
2
u/AKostur Jul 22 '26
I don’t understand what you’re asking for in #1. Heck, I don’t understand what you mean by “I want to do the same thing only using char[]”. Perhaps you mean “how do I do the same thing, but put the result into another C string instead of the screen?” sprintf.
For #2: if one could use +: where would it put the result? (Ignoring the array to pointer decay for the moment)
It seems you have a fundamental misunderstanding how memory management works in C, as well as how C strings work, and how arrays function in C.
11
u/sciencekm Jul 22 '26 edited Jul 22 '26
In C, char name[] = "abc" simply means that name is an address in memory where you have a series of characters.
When you use the + operator, you end up adding to that address. Other languages "hides" (abstracts) as to what + does to objects. C does not. You have to understand memory organization.
For example, with char str[] = "abcdef", str + 2 is the memory 2 steps after str, which happens to be "cdef".
#include <stdio.h>
int main(int ac, char *av) { char *s = "not available";
return printf("argument is %s\n", s + 4 * (ac > 1)); }
The above example will display "argument is not available" or "argument is available", depending on the number of parameters passed when the program is run.
2
u/This_Growth2898 Jul 22 '26
C has no strings. char [] is an array of chars that is used as strings by standard library functions (assuming they end with '\0' guard). You can use + operator for char[], but it has an entirely different meaning:
So, answering the question 2: because + operator for strings in other languages involves memory allocation, and you probably want to do that on purpose if you code in C.
And for the question 1 - check out the *printf (and *scanf) function family; snprintf does most things you want to do with + operator.
2
u/ReallyEvilRob Jul 22 '26
There is no string datatype in C like there is in other languages. Only arrays of char. The standard library is pretty misleading about this issue since it names many of its functions with str or s, implying the existence of strings. Just like how there is no spoon in the Matrix, in C there is no string.
2
u/SmokeMuch7356 Jul 22 '26
The root of the problem is that arrays in C are just dumb sequences of objects; they do not carry any metadata about their size, type, location, or anything else. Once defined they cannot be resized, which is why there's no
+concatenation operator defined for array types, and why subscripting past the end of the array doesn't extend it. Since arrays don't know how big they are, you won't get any kind of "index out of bounds" exception if you try to read or write past the end of an array; you'll just either clobber data or write to unused memory. Array expressions may not be the target of the=assignment operator (we'll get into one reason why below).Strings in C are just sequences of character values including a zero-valued terminator. There is no dedicated
stringtype in C, and all strings are stored in arrays of character type (although not all arrays of character type will contain strings).When you write
what you get in memory looks like this:
That's it. The size of the array is taken from the length of the initializer (4 printable characters plus the terminator). Note that there is no
aobject separate from the array elements themselves; the address ofaand the address ofa[0]are the same.Now, here's where things get fun.
C was derived from Ken Thompson's B programming language. In B, when you declared an array:
an extra word was set aside to store the location of the first element:
The array subscript operation
a[i]was defined as*(a + i)- offsetiwords from the address stored inaand dereference the result.Ritchie wanted to keep B's array behavior, but he didn't want to keep the explicit pointer that it required.
a[i]is still defined as*(a + i), but instead of storing a pointer value,aevaluates to a pointer to the first element of the array. There is a rule in the language that unless it is the operand of thesizeof,typeof, or unary&operators, an array expression will "decay" to a pointer to its first element.And this is one reason why
=is not defined for array types; there's nothing to assign to. There is no objectaseparate from the array elements.So, to write new string values to a character array, you have to call a library function:
A naive implmentation of
strcpywould look like:It copies the contents of the source string pointed to by
sinto the destination array pointed to byd.strcatappends the contents of one string to the end of another; the destination array must be large enough to accommodate the final result (again, this is a naive implementation, not the real thing):1
u/awsq_code Jul 22 '26 edited Jul 22 '26
1
u/Leo0806-studios Jul 22 '26
char[] is not an object like a string (wich doesnt rly exist in C)
instead its an array of characters
char[] implicitly decays to a pointer
so anytime you do arr + arr2 your trying to add two pointers instead of concating two strings.
to concact strings you usualy use a library function (strcat or strcat_n)
1
u/bare_metal_C Jul 22 '26
Every language has a different way of doing things and that is just how printf in c is.
1
u/Sad_Chemical_231 Jul 22 '26
Yeah %d %s %p take some time getting used to But you will get it
1
u/rupertavery64 Jul 22 '26
Therr are no strings in C.
printf takes a pointer to a char array and writes the contents to console until it hits a null terminator
To concatenate a string, you need to allocate a new char array and copy the source strings to it. This is what higher-level languages do.
A char array with predefined size under a certain limit will be created on the stack by the compiler, so you don't need to allocate memory for it.
The compiler knows upfront how much memory the array needs and reserves it on the stack.
When you have a dynamically allocated array that is runtime bound, then you need to allocate it yourself.
1
u/arcfide Jul 23 '26 edited Jul 23 '26
I didn't realize how much I could get ragebaited just by reading, "Why can't you do [use + for string catenation], like you can in any other language?" I mean, none of my favorite languages let you do this. I'm unreasonably upset by this question (not the lack of overloaded +).
1
u/Paul_Pedant Jul 23 '26
To avoid problems with multiple values and format specifiers and unknown lengths, the printf function group has a simple solution.
It has a buffer where it assembles all the parts of your text into one long string before it sends it to the output stream. It might malloc and release that buffer for each call, or keep it for a whole process, or grow it when it needs to. You don't need to know, and it can be different for every version of every stdio library.
Some compilers (and some optimisation levels) even recognise when a printf is simple enough to just emit one string, and call fputs instead. As long at it does what is written n the man page, it is valid C.
1
u/erroneum Jul 25 '26
A bit late to comment, but not every language uses
+for string concatenation, or even has it as an inbuilt operation. PHP has language level support for string concatenation (and an inbuilt string type) using the operator., whereas C++ doesn't have language level support for concatenation or strings, but gives the tools to make a very convincing facsimile thereof (classes and operator overloading). C gives neither of these, so you must explicitly invoke a function which performs string concatenation if that is desired, which might be one which allocates its own memory for the result, or it might work inside a provided character array.0
u/Dry-War7589 Jul 22 '26
All arrays in C are essentially a pointer to the first element. And a pointer is a variable that holds a memory address of some data. And when you use + on pointers you dont add the data at that memory address, but the memory address itself, which is not what you wanted and will cause some form of memory violation, probably. Now printf doesnt have to malloc any char pointers, since char[] is a pointer in itself. Hopefully this helps!
1
u/[deleted] Jul 23 '26 edited Jul 26 '26
[removed] — view removed comment