This one is probably very simple, but I can't seem to get it working.
I have this very simple snippet of code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[100];
char *p = buf;
strcpy(p, "Test string");
printf("%s\n", *p);
}
Which causes a segmentation fault when I run it. GDB outputs:
Program received signal SIGSEGV, Segmentation fault.
0xb76af3b3 in strlen () from /lib/i686/cmov/libc.so.6
But I still don't get it.
Comments would be appreciated, thanks.
When you write
printf("%s\n", *p);
the *p
will be the value at p[0]
which is a character. The printf however is looking for an array of chars, thus causing it to segfault. Remember that in C, strings are just arrays of characters, and arrays are effectively pointers to the first element, this is why you don't need to dereference.
To fix this remove the * to get:
printf("%s\n", p);
You're passing a character to printf; you should be passing the pointer.
char buf[100];
char *p = buf;
strcpy(p, "Test string");
printf("%s\n", p); // p, not *p
Use this:
printf("%s\n", p);
use "p" instead of "*p"
Replace
printf("%s\n", *p);
with
printf("%s\n", p);
When you use %s
, printf expects you to pass a char*
. You are passing a char
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With