In C/C++, Char[] is basically an array of characters. So, if we have something like below :-
char c[] = "hello";
It means, we have an array "c" which has been initialized to string "hello". It is equivalent to following
char c[] = {'h', 'e', 'l', 'l', 'o', '\0'};
It essentially means, that "c" is an array of length 6 (based on the length of string literal). In memory, array is stored in continous memory cells which can be accessed by name "c". A copy of this array is present in stack and just like any other arrays, you can modify its contents, i.e.
c[0] = 'H'; // Perfectly legal
Note, that you can not assign a new string literal to "c" without re-declaring it but can change the individual character by array index.
Char* is a pointer to string literal. In this case "c" is a "pointer to char" and initializes it to point to an object with type "array of char".
char *c = "hello";
One thing to note here is that this constant string is stored in read only memory and its content can not be changed. If you try to modify the result, it would be an undefined behavior. In this case, only the address of this string literal is present in stack.
c[0] = 'H'; // Undefined Behavior
To illlustarte this read-only memory behavior, if you use gcc and objdump, you'll notice that the string "hello" will be in .rodata section (Text section of executable). So, if you try to modify this read only data, it will result in undefined behavior.
pi@rp:~/Data $ gcc -ggdb -std=c99 -c test.c pi@rp:~/Data $ objdump -s test.o | grep -B 1 hello Contents of section .rodata: 0000 68656c6c 6f000000 hello...
Another thing to notice here is that in C, you can't assign a value to a character array after it is initialized. Reason for that is that 'c' is a array holding the address of first element of char array (remember strings are char arrays in C). Second assignment means assign the pointer address of string literal "hello" to "c", which is invalid since "c" is already holding the address of an array. For such cases, it is recommended to use "strcopy" instead.
char c[10]; c = "hello"; // Invalid Statement
Comments
Post a Comment