Generally, the following two statements about char and char * in C are considered confusing and understanding the difference between them is important.
char s_name = "mycplus";
char *p_name = "mycplus";
The first statement puts the literal string “mycplus” in read-only memory and copies the string to newly allocated memory on the stack. This allows you to modify the contents of the array which is holding the string, and it is statically allocated.
The second statement is known as static string allocation and definition. This statement places the string “mycplus” in the read-only parts of the memory and making p_name a pointer to that string. Also, any writing operation on this memory location are illegal. However, the pointer itself can be changed to point to a new location.
Some of the differences between char  and char * are as follow:
- Main difference between both the statements is that s_name is an array where as p_name is a pointer type variable.
- The sizeof(s_name) and sizeof(p_name) are different because memory handling is different in both statements as explained above.
- Variable s_name and it’s address &s_name is same. where as p_name and &p_name are not same.
- The statement s_name=”Program” is invalid while p_name=”Program” is a invalid C statement.
Above statements can be verified using the following C Program.
char s_name = "Hello, World!";
char *p_name = "Hello, World!";
printf("The size of s_name is %lu\n",sizeof(s_name));
printf("The size of p_name is %lu\n",sizeof(p_name));
printf("Print s_name: %lu\n", s_name);
printf("Print &s_name: %lu\n", &s_name);
printf("Print p_name: %lu\n", p_name);
printf("Print &p_name: %lu\n", &p_name);
The output of the program looks similar to the following (depending upon compiler and OS used). The program might show some warnings such as ISO C++ forbids converting a string constant to ‘char*’
The size of s_name is 14
The size of p_name is 8
Print s_name: 140723957079242
Print &s_name: 140723957079242
Print p_name: 4196116
Print &p_name: 140723957079232
If you try to un-comment the statement //s_name="Program"; the program will terminate and show an error message similar one of the following.
01. error: assignment to expression with array type
02. error: incompatible types in assignment of ‘const char ’ to ‘char ’
03. error: array type 'char ' is not assignable