9

为什么这段代码有效?我希望我需要取消引用ptrprintf("%s\n", *ptr);然后才能打印出来,但Segmentation Fault如果我尝试这样做,我会得到一个。

#include <stdio.h>

int main(int argc, char *argv[])
{
        char name[] = "Jordan";
        char *ptr = name;
        printf("%s\n", ptr);
}

希望大家能给我一些见解。

4

6 回答 6

24
于 2013-04-05T19:14:35.867 回答
7

This is because the %s format specifier in the format string you pass to printf means that the corresponding argument should be a string, not a single character. And in C, a string is a pointer to the beginning of a block of characters that has a null character (byte with a value of 0) at the end.

Basically, this works because you're doing exactly what you're supposed to in order to print a string.

于 2013-04-05T19:14:40.273 回答
2

The %s formatter to printf expects a "string", which is really a pointer to a null-terminated array of characters.

That is to say, printf expects you to pass the pointer to it. When you dereference the pointer, it's taking the letter J, whose value in ascii is 74 (decimal), and tries treating that as a pointer to an array. That's an area of memory that's inaccessible, so you get the segmentation violation.

于 2013-04-05T19:15:41.297 回答
1

格式说明符%s告诉printf期望一个指向以空字符结尾的字符数组的指针。这是什么nameptr是。

*name*ptr不是。如果你取消引用它们,你会得到一个单一的char,这基本上是在撒谎printf——导致未定义的行为。

于 2013-04-05T19:14:07.423 回答
0

*ptr is essentially a reference to a single char, not to the string of char's. due to this char * and char[] are essentially the same thing

于 2013-04-05T19:15:05.213 回答
0

When you declare char prt = name thats where you are dereferencing it. the "" here isn't part of the variable just a way to show you want what that variable points to. If you were to put the *prt again in your printf you are doing it twice. name is an array of characters and *ptr is a dereferenced pointer to those characters.

Hope that explaination helps :-)

于 2013-04-05T19:16:27.387 回答