gpt4 book ai didi

c - char和int的指针

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:31 26 4
gpt4 key购买 nike

你好,我有一个简单的问题

char *a="abc";
printf("%s\n",a);

int *b;
b=1;
printf("%d\n",b);

为什么第一个有效而第二个无效?我觉得应该是第一个

char *a="abc";
printf("%s\n",*a);

我认为 a 存储“abc”的地址。那么为什么当我打印 a 时它显示 abc?我想我应该打印 *a 以获得它的值(value)。

谢谢

最佳答案

Why the first one works but the second one doesnot work?

因为首先,您不是要求它打印一个字符,而是要求它打印一个以 null 结尾的字符数组作为字符串。

此处的混淆是您将字符串视为与整数和字符相同的“ native 类型”。 C 不是那样工作的;字符串只是指向一堆以空字节结尾的字符的指针。

如果您真的想将字符串视为原生类型(记住它们实际上不是),请这样想:字符串的类型是 char *,而不是字符。所以,printf("%s\n", a); 之所以有效,是因为您传递的是 char * 以匹配指示 char *< 的格式说明符。要获得与第二个示例相同的问题,您需要传递一个指向字符串的指针,即 char **

或者,%d 的等价物不是 %s,而是打印单个字符的 %c。要使用它,您确实必须向它传递一个字符。 printf("%c\n", a) 会遇到与 printf("%d\n", b) 相同的问题。


来自您的评论:

I think a stores the address of "abc". So why it shows abc when i print a? I think I should print *a to get the value of it.

这就是将字符串作为 native 对象的松散想法落空的地方。

当你这样写的时候:

char *a = "abc";

编译器会存储一个包含四个字符的数组——'a''b''c''\0'——某处,a 指向第一个,a。只要您还记得 "abc" 实际上是一个包含四个独立字符的数组,就可以将 a 视为指向那个东西的指针(至少如果您理解数组和指针运算在 C 中是如何工作的)。但是,如果您忘记了这一点,如果您认为 a 指向包含单个对象 “abc” 的单个地址,您就会感到困惑。


引自GNU printf man page (因为 C 标准不可链接):

d, i

The int argument is converted to signed decimal notation …

c

… the int argument is converted to an unsigned char, and the resulting character is written…

s

… The const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0') …


最后一件事:

您可能想知道 printf("%s", a)strchr(a, 'b') 或任何其他函数如何打印或搜索字符串当没有“字符串”这样的值时。

他们使用的是一个约定:他们接受一个指向字符的指针,并打印或搜索从那里到第一个空值的每个字符。例如,您可以编写一个 print_string 函数,如下所示:

void print_string(char *string) {
while (*string) {
printf("%c", *string);
++string;
}
}

或者:

void print_string(char *string) {
for (int i=0; string[i]; ++i) {
printf("%c", string[i]);
}
}

无论哪种方式,您都假设 char * 是指向字符数组开头的指针,而不是仅指向单个字符,并打印数组中的每个字符,直到您点击空字符。这就是在整个标准库中融入 printfstrstr 等函数中的“空终止字符串”约定。

关于c - char和int的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com