Can someone explain to me what is the difference between:
char* name = "Gerardo";
either
char name[] = "Gerardo";
I would like to know the differences in terms of memory or performance.
Can someone explain to me what is the difference between:
char* name = "Gerardo";
either
char name[] = "Gerardo";
I would like to know the differences in terms of memory or performance.
A fundamental difference is that in the case of the pointer it points to a string literal. Attempting to modify it is undefined behavior.
While in the other case the array contains a copy of the string that is modifiable.
The fact that a string literal is not modifiable allows compilers to make certain optimizations. If a string is repeated in code and is used as a literal, the compiler can use the same copy of the string for all uses, reducing memory usage. It can also be used directly, which is faster.
For example, this C program:
The compiled assembly code (leaving only the relevant parts):
However the same program using arrays :
When compiling it:
To compile those examples I have used
gcc -c -S -O2 fichero.c
(version 5.4.0)Conclusion . If you are not going to modify the string, the alternative of the string literal assigned to a pointer is faster and uses less memory. If you are going to modify the string you should use the array.
Character pointers are normally used to access character strings, since these are built on the basis of an address (that of the first character) and an end-of-string marker (the '\0' character). The declaration of a character pointer follows the usual rules:
String Pointers: Definition, Declaration and Initialization. The declaration of a string can be as follows:
This reserves space for a string of LENGTH characters.
In C, the name of a one-dimensional list is equal to the address of the first element in the list. Once reserved space is available for the string, a pointer to the string can be constructed using the following statements:
Ref.
http://maxus.fis.usal.es/fichas_c.web/07xx_PAGS/0702.html
Pointers to char access character strings with the address of the 1st element in the string, that string ends with
'\0'
(end-of-string character). When you do++
it advances to the next address in the string (next character).char arrays are a pointer to the 1st character of the string. Therefore, from the point of view of how they are stored in memory, there is no difference. The difference is in the syntax, and there using array-type syntax is better, because when using pointer syntax the compiler must resolve the overload of the operator
*
since it is also used for multiplications and that affects performance a bit in execution and compilation .Also using arrays is easier for the human eye. The syntax is more understandable with arrays than with pointers.