r/cprogramming • • Feb 26 '26

What's the best way to make a string variable?

I generally use:
char* string_variable = "text here";
But if there's a better way, let me know.

12 Upvotes

28 comments sorted by

View all comments

Show parent comment

3

u/Freedom_33 Feb 27 '26

What’s the difference here with being declared const?

3

u/bearheart Feb 27 '26

In C, a const variable cannot be modified. It makes the variable read-only.

2

u/Freedom_33 Feb 27 '26

I meant the const char array and const char pointer in their example

1

u/Snatchematician Feb 27 '26

I would have thought that char* s = “foo” gives you a null terminated string (so s[3] is 0) while char s[] = “foo” gives you an array of chars (so s[3] is undefined).

I don’t know C so this might be wrong.

1

u/Jonny0Than Feb 27 '26

It is indeed wrong.  The array also includes the null terminator.

1

u/Snatchematician Feb 27 '26

Is there any difference between the two declarations?

1

u/Jonny0Than Feb 28 '26

Yes.  If you apply sizeof to them you will get different results. And they have different semantics if this is in a function scope.  The array form will copy data around, the pointer form does not.

1

u/Swipsi Feb 28 '26

So the size of the char* returns the size of a char pointer, but the size of s[] would return the size of a char since thats what the first array element is pointed on by s[]?

1

u/Jonny0Than Feb 28 '26

No, sizeof when applied to an array returns the size of the entire array. You do have to be careful because some things that look like arrays are not arrays, like void foo(char str[])

1

u/Jonny0Than Feb 27 '26

I think it depends on what scope it’s in. At global scope there should be very little difference, other than the behavior of sizeof.  At function scope it’s a huge difference, the compiler will place the array on the stack and copy the characters from readonly memory into it.