Why not the same? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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));

11th Jun 2021, 1:47 AM
abhinav
abhinav - avatar
6 Answers
+ 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 ^^
11th Jun 2021, 3:25 AM
visph
visph - avatar
+ 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
11th Jun 2021, 3:21 AM
Lofty
Lofty - avatar
+ 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'.
11th Jun 2021, 3:32 AM
Lofty
Lofty - avatar
+ 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)
11th Jun 2021, 2:07 AM
visph
visph - avatar
+ 1
a value wich cause the segmentation fault (access of memory unauthorized)
11th Jun 2021, 2:41 AM
visph
visph - avatar
+ 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.
11th Jun 2021, 7:27 AM
Calvin Thomas
Calvin Thomas - avatar