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";
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.
String initialization can be done in two ways: Object Initialization. Direct Initialization.
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.
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.
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 ".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With