Can someone please explain to me why this code gives a Segmentation Fault:
char string[] = "this is a string";
char * string2 = "this is another string";
printf("%s\n",string );
printf("%s\n", string2);
printf("string[2]= %s, string2 = %s\n", string[2], &string2 );
It also gives the same error when I try to print
*string2 or *string2[2] or &string2[2]
I am really confused about this, likewise examples I see on websites seem to print but not this one.
The first two are fine but in the last one you probably want:
printf("string[2]= %c, string2 = %p\n", string[2], (void *)&string2 );
^ ^
You are getting a segmentation fault because you are tricking printf
into interpreting a small integer ( string[2]
) as a pointer (that's what %s
expects).
char * string2 = "this is another string";
declaration causes string2
point to t
(first character of string) and that doesn't mean *string2
is entire string (On derefrencing string2
),ie, "this is another string"
. If you will try to print *string2
with %s
, it will cause segmentation fault but with %c
it will print t
.
To print a pointer use %p
specifier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.