+ 1
Why not the same?
Why does the first one gives segmentation while the second doesn't? (1) char *p = {'a', 'b', 'c', '\0'}; printf("%c", *(p + 1)); (2) char *p = "abc"; printf("%c", *(p + 1));
7 Réponses
+ 4
abhinav the value is the source of the error because you try to assign it to pointer and that value point to unauthorized memory ^^
+ 3
p holds the address, in your code it will hold the value of 'a', which is 97.
So, p holds 97, you're accessing address 97 which is invalid address, that causes undefined behavior.
https://code.sololearn.com/conX1xvcy6Hs/?ref=app
+ 3
Initializer lists are used for aggregate data types like arrays and structures, when you want to assign more values at once, that's the point.
Using these lists with pointer doesn't work, since pointer holds one value, an address.
I can assume, that you have this question because arrays can be initialized with these brace initialized lists and with literal constants, but notice that these two r-values are different type:
char arr[] = {'a', 'x', '\0'};
here r-value is a list, compound type, used to initialize aggregate types
char* arr = "ax" ;
here r-value is array of characters, which will decay into the pointer to a character.
So, pointer will work only in the second case "ax", it will hold the address of 'a'.
+ 2
in (1) curly braces notation is used to initialize an array, but you initialize a pointer
in (2) you initialize the pointer with another pointer (wich point to first char of string literal)
+ 1
a value wich cause the segmentation fault (access of memory unauthorized)
+ 1
abhinav I don't know anything about the first code snippet (possibly an error?) but I do know about the latter. String literals in C are meant to be constant; they're stored in the code segment of the memory allocated to C and they are read-only (for proof, just check the address value of a local variable and a string literal in C; you'd notice a significant difference between the two values). In my opinion, curly braces are used just to initialize arrays.
P.S. There is nothing like a string data-type in C. So, "abc" returns the pointer to the first char element of the character array, which is what makes up what we refer to as a <string>. I hope that I haven't typed anything vague or wrong.