Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration?

Do these two lines of code achieve the same result? If I had these lines in a function, is the string stored on the stack in both cases? Is there a strong reason why I should use one over the other, aside from not needing to declare the null terminator in the first line of code?

char  s[] = "string";
char* s   = "string\0";
like image 479
aoeu Avatar asked Oct 29 '10 11:10

aoeu


People also ask

How is string pointer initialized in C?

The pointer string is initialized to point to the character a in the string "abcd" . char *string = "abcd"; The following example defines weekdays as an array of pointers to string constants. Each element points to a different string.

What are two ways to initialize a string?

String initialization can be done in two ways: Object Initialization. Direct Initialization.

How do you declare a string as a pointer?

In the following code we are assigning the address of the string str to the pointer ptr . char *ptr = str; We can represent the character pointer variable ptr as follows. The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000.

What is a string How are strings declared and initialized in C language?

Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.


2 Answers

No, those two lines do not achieve the same result.

char s[] = "string" results in a modifiable array of 7 bytes, which is initially filled with the content 's' 't' 'r' 'i' 'n' 'g' '\0' (all copied over at runtime from the string-literal).

char *s = "string" results in a pointer to some read-only memory containing the string-literal "string".

If you want to modify the contents of your string, then the first is the only way to go. If you only need read-only access to a string, then the second one will be slightly faster because the string does not have to be copied.


In both cases, there is no need to specify a null terminator in the string literal. The compiler will take care of that for you when it encounters the closing ".

like image 81
Bart van Ingen Schenau Avatar answered Oct 12 '22 01:10

Bart van Ingen Schenau


The difference between these two:

char a[] = "string";
char* b = "string";

is that a is actually a static array on stack, while b is a pointer to a constant. You can modify the content of a, but not b.

like image 34
Šimon Tóth Avatar answered Oct 12 '22 01:10

Šimon Tóth