开发者

C: Segmentation Fault while using printf

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>
#inclu开发者_如何学Gode <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.


just pass the string(the pointer):

printf("%s\n", p);

If you want to print the first char, then:

printf("%c\n", *p);


%s causes printf() to dereference *p. Suppose the string was "Test string". Then on my Solaris sparc box: (in a test program) p would be "aimed at" the address 0x54657374. The probability of that particular address being part of your process space is next to zero.

That is what caused the SIGSEGV signal (segfault).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜