c - Do these statements about pointers have the same effect?

ID : 274488

viewed : 83

Tags : cpointersc





Top 5 Answer for c - Do these statements about pointers have the same effect?

vote vote

90

No.

char  str1[] = "Hello world!"; //char-array on the stack; string can be changed char* str2   = "Hello world!"; //char-array in the data-segment; it's READ-ONLY 

The first example creates an array of size 13*sizeof(char) on the stack and copies the string "Hello world!" into it.
The second example creates a char* on the stack and points it to a location in the data-segment of the executable, which contains the string "Hello world!". This second string is READ-ONLY.

str1[1] = 'u'; //Valid str2[1] = 'u'; //Invalid - MAY crash program! 
vote vote

81

No. The first one gives you a pointer to const data, and if you change any character via that pointer, it's undefined behavior. The second one copies the characters into an array, which isn't const, so you can change any characters (either directly in array, or via pointer) at will with no ill effects.

vote vote

79

No. In the first one, you can't modify the string pointed by myString, in the second one you can. Read more here.

vote vote

60

It isn't the same, because the unnamed array pointed to by myString in the first example is read-only and has static storage duration, whereas the named array in the second example is writeable and has automatic storage duration.

On the other hand, this is closer to being equivalent:

static const char actualString[] = "hello"; char* myString = (char *)actualString; 

It's still not quite the same though, because the unnamed arrays created by string literals are not guaranteed to be unique, whereas explicit arrays are. So in the following example:

static const char string_a[] = "hello"; static const char string_b[] = "hello"; const char *ptr_a = string_a; const char *ptr_b = string_b; const char *ptr_c = "hello"; const char *ptr_d = "hello"; 

ptr_a and ptr_b are guaranteed to compare unequal, whereas ptr_c and ptr_d may be either equal or unequal - both are valid.

vote vote

55

Top 3 video Explaining c - Do these statements about pointers have the same effect?







Related QUESTION?