I know this is a very basic question. I am confused as to why and how are the following different.
char str[] = "Test"; char *str = "Test";
char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.
The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
char *A[] is an array, and char **A is a pointer. In C, array and pointer are often interchangeable, but there are some differences: 1. with "char *A[]", you can't assign any value to A, but A[x] only; with "char **A", you can assign value to A, and A[x] as well.
char str[] = "Test";
Is an array of chars
, initialized with the contents from "Test", while
char *str = "Test";
is a pointer to the literal (const) string "Test".
The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test"
, while the pointer simply refers to the contents of the string (which in this case is immutable).
The diference is the STACK memory used.
For example when programming for microcontrollers where very little memory for the stack is allocated, makes a big difference.
char a[] = "string"; // the compiler puts {'s','t','r','i','n','g', 0} onto STACK char *a = "string"; // the compiler puts just the pointer onto STACK // and {'s','t','r','i','n','g',0} in static memory area.
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