I'm pretty new to C and I got stuck with pointers.
My question is this: when do I use the * when accessing string pointer, and when don't I use it?
I understood that when I want to access the variable the pointer points to address I don't use the *, but when I want to access the variable's value I do add the *. But the code below
char str1 = "Hello", str2 = "World"; char * ptr1, * ptr2; ptr1 = &str1; ptr2 = &str2; printf("%s %s\n", str1, str2); printf("%s %s\n", ptr1, ptr2); printf("%s %s\n", *ptr1, *ptr2);
produces the following output:
Hello World Hello World Segmentation Fault
I get a 139 exit code when executing this program. So it seems as if the * doesn't work here. I'll be very happy for any help regarding this.
%s in your first
printf argument means that a string is expected at that place in the argument list. In C, a string is an array of characters, and usually is described by a pointer to the first element of that array, i.e. to the first character.
Hence, the last line of your code is wrong. You are dereferencing the first character of your string here:
*ptr1 yields the first character of your first string, i.e. yields the value
72 (the ASCII code of the letter
By putting this as string argument for your
printf, the situation gets even worse: Here, a string is expected, i.e. a pointer to the first character of the respective character array, which means that the value
72 will be cast (expanded) to whatever the pointer size of your target environment is.
If the pointer size of your target environment is 32 bits, you will end up with this:
printf("%s %s\n", 0x00000048, ...); /* 72 dec is 48 hex */
So you are telling
printf that it will find the first string at memory location 0x00000048, which of course is wrong.
To stress it again:
*ptr1 gets you the character which is stored in memory location
ptr1, but not "the string". Actually, there is no
string data type in C, so you can't get a string by dereferencing a pointer.