Is there a difference between:
char string = "name";
const char* point = string;
vs
const char string[] = "name";
Will you please explain the difference too?
Is there a difference between:
char string = "name";
const char* point = string;
vs
const char string[] = "name";
Will you please explain the difference too?
Yes.
The first simply points to a read only section of memory, the declaration really should be:
const char* string = "name";
The second creates an array long enough to hold the string "name" (so, four characters plus one for the null terminator) and copies the string inside the allocated space.
#include <stdio.h>
int main(int argc, const char** argv)
{
const char *a1 = "hello";
const char a2[] = "hello";
char* b1;
char* b2;
b2 = (char*) a2;
*b2 = 'c';
puts(b2);
b1 = (char*)a1;
*b1 = 'c';
puts(b1);
return 0;
}
b2 will display 'cello' properly. b1 will cause a segmentation fault.
This is due to b1 is stored in text segment of the code, whereas b2 is stored in data segment.
i hope i didnt mess it up...
also, compiler can do magic to make this invalid by recognizing that something is declared on text segment, but is accessed in code, so C sometimes catches on, and changes declaration to data segment