user2847666
user2847666

Reputation: 119

How to Print Pointers in c?

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.

Upvotes: 3

Views: 2072

Answers (2)

haccks
haccks

Reputation: 105992

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),i.e, "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.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

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).

Upvotes: 10

Related Questions