在昨天的问题之后,我进一步尝试了指针。具体来说是int (*) [n]类型的指针。
这是我写的一些代码:
#include <stdio.h>
int main(void)
{
int a[5] = {1, 2, 3, 4, 5};
int (*p) [5] = &a;
int *q = a;
printf("\t\t\t\t\tp\t\tq\n\n");
printf("Original Pointers: \t%20d%20d", p, q);
printf("\n\n");
printf("Incremented Pointers:\t%20d%20d", p+1, q+1);
printf("\n\n");
printf("Pointer values: %20d%20d", *p, *q);
printf("\n\n");
return 0;
}
以下是它的输出:
p q
Original Pointers: 132021776 132021776
Incremented Pointers: 132021796 132021780
Pointer values: 132021776 1
当指针
p
递增时,每次跳过20个位置。这是因为它是int(*)[5]
类型的指针,因此在数组中跳过sizeof(int) * number of columns
。无论
p
和q
具有相同的值(但不同的类型),但是当使用间接操作符与p
一起使用时,我没有得到数组第一个单元格的值,而是得到了p
本身的值。为什么会这样?当我使用
int *p = &a
时,它会引发警告(因为指针类型不同),但稍后当我使用间接操作符与p
一起使用时,我可以打印出数组中第一个单元格的值。这是因为当我将&a
赋值给p
时,它将&arr
的类型(即int (*) [5]
)转换为int *
类型,然后再分配给p
吗?
gcc -std=c11 -pedantic-errors
进行编译,以使其正常运行。 - Lundin-pedantic-errors
是否存在。我在版本 4.9.1 中进行了测试:warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
。无论我是否添加-Wall -Wextra -pedantic-errors
,我都会收到此警告。 - Lundin