gpt4 book ai didi

c - C中存储字符串的指针数组

转载 作者:行者123 更新时间:2023-12-02 08:23:23 25 4
gpt4 key购买 nike

我是C语言的新手。最近我遇到了几个关于指针的问题。想寻求您的帮助。非常感谢~

下面是一个代码块:

char *a[2];
a[0] = "blah";
a[1] = "hmm";
printf("%s %d\n", a[0],a[0]);
printf("%s %d\n", a[1], a[1]);

上述代码的输出是“blah”,a[0]的地址,“hmm”和a[1]的地址。

第一个问题是:a[0] 应该是一个指针,它应该包含一个地址。但是这里给a[0]赋值的是字符串,就奇怪了。为什么这有效?

第二个问题:a[0]是一个指针,所以printf("%d",a[0])自然会打印出a[0]的地址。但是,printf("%s",a[0]) 打印的是"blah",也就是地址中存储的字符串,其地址值等于a[0]中存储的值。直觉上我认为打印字符串的正确语法是使用 printf("%s",*(a[0])) ,结果是执行错误。那么为什么 printf("%s",a[0]) 会给出所需的字符串结果呢?

期待您的回答,非常感谢您的帮助~

最佳答案

  1. printf("%s %d\n", a[0],a[0]);

您应该使用 %p 来打印指针。 %d 是打印整数。


  1. a[0] is supposed to be a pointer, which should contain an address. But here a[0] is assigned with a string, which is strange. Why this works?

是的。 a[0] 应该是一个指针,它应该包含一个地址。将 a[0] 分配给字符串是可行的,因为字符串常量是指向它的第一个成员的指针。即“blah”是指向 b

的指针

验证:

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

  1. a[0] is a pointer, therefore printf("%d",a[0]) will naturally print the address of a[0]. However, printf("%s",a[0]) prints "blah", which is the string stored in the address whose address value is equal to the value stored in a[0].

printf("%p", a[0]) 将打印 a[0] 的值,这是一个地址,printf("% s", a[0]) 将打印从地址 a[0] 开始线性存储的字符串。这是因为使用了 format specifier

%p 表示将值打印为地址(指针),其中 %s 表示打印从 a[0] 开始存储的所有字符直到遇到 \0 字符。


  1. Intuitively I think the correct syntax to print the string is to use printf("%s",*(a[0])) , which turns out to be execution error.

a[0] 是一个指针,一个地址。我们在该地址存储了 "blah" 中的字符 b。所以 *(a[0]) 的类型是 char wheres "%s" expects type char * (指向字符的指针)。所以类型不匹配。

要获得清晰的想法:

printf("%c",*(a[0]));  

这将打印存储在 a[0] 的字符,因为我们正在使用 * 运算符取消引用 a[0]

关于c - C中存储字符串的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671753/

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