Problem with declaration of an array of pointers

扶醉桌前 提交于 2019-12-12 16:50:07

问题


When i execute this code

#include<stdio.h>

int main() {
 int (*x)[5];
printf("\nx = %u\nx+1 = %u\n&x = %u\n&x + 1 = %u",x,x+1,&x,&x+1);
}

This is the output in C or C++:

x = 134513520
x+1 = 134513540
&x = 3221191940
&x + 1 = 3221191944

Please explain. Also what is the difference between:

int x[5] and int (*x)[5] ?


回答1:


  • int x[5] is an array of 5 integers
  • int (*x)[5] is a pointer to an array of 5 integers

When you increment a pointer, you increment by the size of the pointed to type. x+1 is therefore 5*sizeof(int) bytes larger than just x - giving the 8048370 and 8048384 hex values with a difference of 0x14, or 20.

&x is a pointer to a pointer - so when you increment it you add sizeof(a pointer) bytes - this gives the bf9b08b4 and bf9b08b8 hex values, with a difference of 4.




回答2:


  1. int x[5] is an array of 5 ints
  2. int (*x)[5] is a pointer to an array of 5 ints
  3. int* x[5] is an array of 5 pointers to ints



回答3:


int (*x)[5];

declares a pointer to an array.

From the question title, you probably want

int* x[5];

instead, which declares an array of pointers.

int x[5];

declares a plain old array of ints.




回答4:


int x[5];

declares an array of five ints.

int (*x)[5];

declares a pointer to an array of 5 ints.

You might find cdecl.org useful.



来源:https://stackoverflow.com/questions/5571847/problem-with-declaration-of-an-array-of-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!