[英]pointer arithmetic with pointer to array
我正在尝试使用指向数组的指针进行指针算术运算,但由于无法正确取消对指针的引用,因此得到了错误的值。 这是代码:
#include "stdlib.h"
#include "stdio.h"
int main()
{
int a[] = {10, 12, 34};
for (int i = 0; i < 3; ++i)
{
printf("%d", a[i]);
}
printf("\n");
int (*b)[3] = &a;
for (int i = 0; i < 3; ++i)
{
printf("%d", *(b++));
}
printf("\n");
return 0;
}
在第二个中,因为我无法打印正确的值。
即使我写也不行
printf("%d", *b[i]);
我想看看如何使用b ++和b [i]语法正确打印。
您已将b
声明为指向3个整数的数组的指针,并且已使用a
地址对其进行a
初始化。
int (*b)[3] = &a;
在第一循环中,您将打印的第一个元素a
阵列,但这时你会移动3*sizeof(int)
,并引发未定义的行为试图打印任何存在。
要正确打印它:
int *b = a;
// int *b = &a[0]; // same thing
// int *b = (int*)&a; // same thing, &a[0] and &a both points to same address,
// though they are of different types: int* and int(*)[3]
// ...so incrementing they directly would be incorrect,
// but we take addresses as int*
for (int i = 0; i < 3; ++i)
{
printf("%d", (*b++));
}
以下应该工作:
printf("%d\n", *( *b+i ));
// * b + i将为您提供从第一个元素a [0]的地址开始的每个连续地址。
//外部的'*'将为您提供该位置的值。
代替:
printf("%d", *(b++));
gcc会在第二个for循环中抱怨格式:它将告诉您format specifies type 'int' but the argument has type 'int *
您从a到b的分配应如下所示:
int *b = a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.