简体   繁体   English

指向数组的指针算术

[英]pointer arithmetic with pointer to array

I'm trying to do pointer arithmetic with a pointer to array, but I get a wrong value since I can't dereference the pointer properly. 我正在尝试使用指向数组的指针进行指针算术运算,但由于无法正确取消对指针的引用,因此得到了错误的值。 Here is the code: 这是代码:

  #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;
  }

In the second for I can't get to print the correct value. 在第二个中,因为我无法打印正确的值。

It doesn't work even if I write 即使我写也不行

printf("%d", *b[i]);

I'd like to see how to print correctly using the b++ and the b[i] syntax. 我想看看如何使用b ++和b [i]语法正确打印。

You have declared b to be a pointer to arrays of 3 integers and you have initialized it with address of a . 您已将b声明为指向3个整数的数组的指针,并且已使用a地址对其进行a初始化。

int (*b)[3] = &a;

In the first loop you will print the first element of a array but then you will move 3*sizeof(int) and trigger undefined behavior trying to print whatever there is. 在第一循环中,您将打印的第一个元素a阵列,但这时你会移动3*sizeof(int) ,并引发未定义的行为试图打印任何存在。

To print it correctly: 要正确打印它:

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++));
}

The following should work: 以下应该工作:

printf("%d\n", *( *b+i ));

// * b + i will give you each consecutive address starting at address of the first element a[0]. // * b + i将为您提供从第一个元素a [0]的地址开始的每个连续地址。
// The outer '*' will give you the value at that location. //外部的'*'将为您提供该位置的值。

instead of: 代替:

printf("%d", *(b++));

gcc will complain about the formatting in the second for loop: it will tell you format specifies type 'int' but the argument has type 'int * gcc会在第二个for循环中抱怨格式:它将告诉您format specifies type 'int' but the argument has type 'int *

your assignment of a to b should look like this: 您从a到b的分配应如下所示:

int *b = a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM