r/C_Programming • u/invokeinterface • Jun 24 '26
Question Two different ways to store strings
What's the difference between storing a string as a char* or a char[]? I know they're stored differently (I think arrays use the stack,) but other than that I'm not so sure.
What's weirder is that I'm pretty sure you can use pointers as arrays whenever you want.
EDIT: I know what a pointer is and how char* as strings work, I'm just not sure why there's the option
25
Upvotes
70
u/ByMeno Jun 24 '26 edited Jun 24 '26
In C, char *b and char a[] are not the same thing but [] can decay to *
char *b = "hello";
char a[] = "hello";
b is a pointer variable (typically 4 bytes on 32-bit systems and 8 bytes on 64-bit systems). It stores the address of the first character of a string literal. sizeof(b) gives the size of the pointer itself, not the length of the string.
a is an array containing a copy of the string. The compiler allocates enough space for all characters plus the null terminator ('\0'). For "hello", sizeof(a) is 6.
Another important difference is modifiability:
char *b = "hello";
b[0] = 'H'; // Undefined behavior
The string literal is typically stored in read-only memory.
char a[] = "hello";
a[0] = 'H'; // OK
Since a is an array containing its own copy of the characters, its contents can be modified.
Arrays also automatically decay to pointers in many expressions, which is why they often seem similar, but an array is not a pointer.
9
u/HashDefTrueFalse Jun 24 '26 edited Jun 24 '26
Others have given good answers on the difference between * and [] so I'll just comment on this bit:
Kind of. Arrays and pointers are different things and generated access code is different depending on which you have. A pointer has an extra bit of indirection when compared to an array. A pointer (in the context of arrays) stores the address of the first element at a secondary address (the address of the pointer), whereas the array name aliases (is) the address of the first element directly.
It's more accurate to say that the name of an array decays to a pointer to the first element in places, like in expressions (e.g. when passing an array as a function argument, which is why it doesn't really matter if you use [] or * syntax in function parameter lists). In practice this is most places and it's fairly intuitive when programming (IMO, I suppose). This was just a C design decision to avoid copying whole arrays around etc.
Edit: You can see this here if you like: https://godbolt.org/z/K89csq7hn The array takes one load to get the first value. The pointer takes two. (Also you can plainly see that the a symbol aliases the first of 40 zero bytes whereas b is only the size of a pointer.)
8
u/pfp-disciple Jun 24 '26 edited Jun 24 '26
I suggest setting aside "string" for a moment, and think of "array of
char" (which is really all a C string is).So,
char s1[10]just declares an array of 10chars. Assuming this is just a normal variable declaration, the compiler will allocate (on the stack - I think always, but even if not, you can get away with assuming that for now) that automatically.If your declare
char *s2, you will have a variable that points to achar. This does not allocate thechar, and note that in this declaration, the pointer is uninitialized. This pointer can point to something on the stack, or on the heap (e.g viamallocorstrdup), often on the heap.Now, recall that C doesn't really have a data type called string. It has a convention that an array of
charthat ends with a NIL character (ASCII 0, or'\0') can be treated as a string. So, something likechar *s = "hello";does the following:,chars long (hello plus the NIL). Almost certainly not on the stack nor the heap.2
u/Consistent_Reply8522 Jun 24 '26
Here’s maybe a different / fun way to convey the value of char[] in addition to char*.
Your task is to store “abc” (exactly 3 bytes) in contiguous memory. How would you do it if you had access only to char* and not char[]?
Hope that helps.
2
u/Living_Fig_6386 Jun 24 '26
char *is a pointer to a character, andchar[]is an array of characters. You don't "store a string" as achar *, you use the character pointer as a reference to the first character of an array of characters. Achar[], array of characters, is a piece of memory that you will treat as an array of characters, and it has a fixed length; it's what achar *is pointing too. Note that achar *can also be pointing to memory allocated usingmalloc()orcalloc().Also important, in C, a string is an array of characters that ends with the special character '\0' to mark the end.
You can do the following:
... in both cases, the
"string"is an array of characters:{'s', 't', 'r', 'i', 'n', 'g', '\0'}. and a and b both point to the first letter of the array. HOWEVER, if you didsizeof(a), you'd get the pointer size (4 or 8 bytes), andsizeof(b)would give you the length of the array (7 bytes) because you declared one as a pointer and the other as an array.Another important distinction,
ais pointing to a string constant that the compiler can store in an area that is considered read-only. Modifying the string pointed to by a could generate an error. However,bis created as an array that has that constant string copied into it, and modifying that string is allowed.2
u/TheChief275 Jun 24 '26 edited Jul 02 '26
Stop thinking in terms of the stack and heap; those are largely just made up words irrelevant to the language's semantics and they are holding you back. All there is is just memory.
The only difference between a T* and a T[N] is that a T* stores an indirect buffer while a T[N] stores a direct buffer. So for the T* there is always an indirection between accessing each element:
which is equivalent in layout to a T (*)[N] in this case (although not in type/semantics):
while a T[N] is equivalent to a struct or tuple of T's, and stores them in place:
This becomes clear when looking at the sizeof a T* and e.g. a T[2], where sizeof(T*) = sizeof(void*) while sizeof(T[2]) = sizeof(T)*2. This is also why the N in T[N] needs to be constant (before VLAs) as sizeof is guaranteed to be a compile-time value (again, before VLAs).
There is also a literal T[], without the length specified, which is a flexible size array (note that it's not the same as a VLA). The only use of this array is to be the last field of a struct, it's not allowed anywhere else. It functions exactly like the T[N], but it forces instances of its containing struct to only be present in the form of pointers. This is because, like T*, the size of the buffer is only determined at runtime. Take for instance this struct:
say we use dynamic allocation to create an instance, we would do so like this:
causing the following layout:
2
u/Feisty_War80 Jun 24 '26 edited Jun 24 '26
I finally have enough knowledge to answer this.
char* is a pointer. So lets say you do:
char* x=&var; (same as char *x=&var)
x is a "pointer variable", aka it is a variable that stores the address of another variable. In this case, it stores the address of var, as you may know, & is used to check for the memory location.
So instead of doing scanf("%c",&var), you can do scanf("%c",x)
When you do for a string/array, you dont need the pointer variable as the first element of the array automatically points to the entire array.
char[] (thats the wrong syntax):
char x[]="Hello invokeinterface!";
x is allocated a certain amount of bytes, in which the string is stored. you can write char x[50], or just leave it blank. But do remember that if you leave it blank, you will have to write into the variable at the declaration phase itself. You cant do like
char x[];
x="Hello";
this is because x got allocated no memory. You cant do:
char x[50];
x="Hello";
this is because when you declare x, it gets stored as [0] [0] [0] [0] [0] (49 times) and ['\0'], so you will have to manually reassign each index by using x[0]='H'; and so on, or you can just use strcpy if u have access to string.h.
So in a nutshell, char* is a pointer variable and char x[] is used to define an array, in this case a string.
1
u/detroitmatt Jun 25 '26
the difference between pointers and arrays is subtle but important.
an array is stored in memory as a series of elements all stored back to back, one after the other. When you write
int arr[4];, the compiler allocates enough room to store 4 ints and you can usearrto refer to that region of memory.sizeof(arr)will be 4 *sizeof(int), because the 4 was part of the declaration. Note that if your variable is declared asint arr[], the size isn't part of the declaration andsizeofgets a little weirder-- more on that in a sec.But what happens if you want to pass that array to somewhere else in the program? function parameters have to be passed in some way, usually either by storing them in registers or by pushing them on top of the stack. But what if one of the parameters is a
double[65536]? That's a lot of memory, it won't fit in registers, and it would be very bad performance to try to make a second copy on top of the stack. So instead of actually passing the array itself, what gets passed is a pointer to the front of the array. We say the array "decays" to a pointer. The original array stays where it was, and the function you call gets a pointer to that address.So going back to
int arr[]. This is a bit of the language telling a little white lie and acting like your variablearris an array. It's not, it's a decayed array, a pointer.int arr[]is the same thing asint *arr, because the size information is no longer there. What that means is that if you try to dosizeof(arr), instead of being the number of elements in the array, it'll besizeof(int*)(that is, the size of a pointer on your platform).You mentioned in your post about "using the stack". Both int[] and int* can be "on the stack" or "on the heap", either way is possible, because this is about types, which only exist at compile time, and stack/heap locations only exist at runtime. By the time the stack/heap exists, the type information has been compiled out of the program.
Inside
foo, foops is stored on the heap, and it's (declared as) an int[400] (but in fact, it's actually an int* andsizeof(foops)will besizeof(int*))1
u/SmokeMuch7356 Jun 26 '26
The difference is best illustrated with an illustration. Assume the following declarations:
What you get in memory looks something like this (addresses are just for illustration):
The declaration for
strallocates enough storage to contain the string"hello". You can modify the contents of this array to your heart's content, as long as it fits within 6 bytes:You cannot extend the array, and you can't assign a different array object to
str.The declaration for
ptrallocates enough storage to contain the address of the string literal"hello". Storage for the string itself is taken from somewhere else (usually a read-only data segment).You can assign the pointer to point to different array objects:
You can point to dynamically-allocated memory:
which can be resized as necessary:
The array subscript operation
a[i]is defined as*(a + i); starting with the address value given bya, offsetielements and dereference the result. Ifais a pointer expression (char *a = "foo";), then it just evaluates to the pointer value stored ina. Ifais an array expression (char a[] = "foo";), then it is converted to a pointer expression and evaluates to the address of the first element of the array.1
u/Environmental-Ear391 Jun 28 '26
pointers refer to dynamic allocated memory, arrays refer to immediate storable...
there is only a difference in the semantic usage, actual implemented string usage doesn't seem to differ all that much.
struct randomp { char *string; };
struct randoms { char string[16]; };
sizeof(randomp) vs sizeof(randoms)
4 or 8 vs 16 appropriately.