[英]Array pointers in c programming
我不知道为什么输出给我每个单词的第一个字母,不应该给我整个单词吗?
#include <stdio.h>
int main()
{
char *fruit[] = {
"watermelon", "banana", "pear", "apple"};
int x;
for(x = 0;x<4; x++){
putchar((** fruit) +x );
putchar('\n');
}
return 0;
}
putchar
将单个字符打印到标准 output - 它不能用于打印整个字符串(除非您手动迭代该字符串,并单独打印每个字符)。
这个表达
(** fruit)
产生第一个字符串的第一个字符。 然后每次迭代都将x
添加到此字符的值。 (即'w' + 0 == 'w'
... 'w' + 3 == 'z'
)。
取而代之的是,使用puts
打印一个完整的字符串(后跟换行符),并使用数组订阅使代码更具可读性( fruit[x]
相当于*((fruit) + (x))
) 。
#include <stdio.h>
int main(void)
{
char *fruit[] = {
"watermelon", "banana", "pear", "apple"
};
int x;
for(x = 0; x < 4; x++) {
puts(fruit[x]);
}
return 0;
}
代码有一些问题。
数组是传染性 memory 位置中相同数据类型的一组变量。
int a[4] = {1, 4, 2, 5};
这意味着元素 1、2、4、5 存储在连续的 memory 位置,并且组由名称“a”表示。
当您引用数组名称时,您指的是数组中第一个元素的 memory 位置。 现在,如果您在代码中引用a ,您指的是 &a[0]。
a -> address of first element.
a + 1 -> address of second element.
如果你取消引用它们。
*a -> first element in the array
*(a + 1) -> second element in the array
在你的情况下,
char *fruit[] = {
"watermelon", "banana", "pear", "apple"};
fruit 是字符指针数组。
*fruit -> "watermelon"
*(fruit + 1) -> "banana"
同样的方式,
** fruit 表示您将第一个元素取消引用两次。 首先取消引用将给出“西瓜”。 第二次取消引用应该给出'w'。
在循环中,你总是使用 (**fruit) ,它总是会给你字符 'w'。
(** fruit) + 0 -> 'w' (you are adding 0 to 'w')
(** fruit) + 1 -> 'x' (you are adding 1 to 'w')
(** fruit) + 2 -> 'y' (you are adding 2 to 'w')
(** fruit) + 3 -> 'z' (you are adding 3 to 'w')
第二个问题是 putchar() 将一个字符打印到 output。 您需要使用 puts() 或 print()。
修改后的代码如下。
#include <stdio.h>
int main()
{
char *fruit[] = {
"watermelon", "banana", "pear", "apple"};
int x;
for(x = 0; x < 4; x++){
printf("%s", *(fruit + x));
printf("\n");
puts(*(fruit + x));
putchar('\n');
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.