为什么我在2D数组中获得相同的地址?

时间:2015-03-13 21:59:08

标签: c arrays memory-address

最近,我在为2D数组赋值时遇到了这个问题。为了表示我的问题,我创建了小C代码。我正在使用QT创建者(社区)3.3.0和minGW 4.9.1 32位。

#include <stdio.h>
int main(void){
double m[2][2];
for (int i = 0 ; i<3; i++){
    for(int j=0; j<3; j++)
         printf("%p[%d][%d]     ", (void*)&m[i][j],i,j);
    printf("\n");
 }
return 0;
}

作为输出,我得到了内存地址

0028FE98[0][0]     0028FEA0[0][1]     0028FEA8[0][2]
0028FEA8[1][0]     0028FEB0[1][1]     0028FEB8[1][2]
0028FEB8[2][0]     0028FEC0[2][1]     0028FEC8[2][2]

您可以看到不相等的数组项具有相同的地址。因此,当我为例如[1] [2]赋值时,[2] [0]中的值也会改变。

请告诉我如何解决这个问题。非常感谢你。

4 个答案:

答案 0 :(得分:5)

你的数组应该是3x3:

double m[3][3];

或者你的循环应该只迭代两次,而不是三次。

您现在拥有的代码会访问某些超出范围的内存,从而导致未定义的行为。

答案 1 :(得分:1)

您的for条件错误。应该是i<2j<2。试着,你会发现一切都会好的。

为什么有相同的指针?因为内存中的表(1d,2d,3d不重要)是一个内存块。所有尺寸都是&#34;在一行&#34;当你写这样的东西时

double tab[2][2];

tab[0][1] = 1; // that's the same as *(tab + 0*sizeof(double)*2 + 1*sizeof(double)) = 1;
tab[1][1] = 2; // that's the same as *(tab + 1*sizeof(double)*2 + 1*sizeof(double)) = 2;

所以你可以看到你有这个

double m[2][2];

m[1][2]  // that's the same as (m + 1*sizeof(double)*2 + 2*sizeof(double)) => (m + 4*sizeof(double)) ;
m[2][0]  // that's the same as (m + 2*sizeof(double)*2 + 0*sizeof(double)) => (m + 4*sizeof(double));

这就是为什么那是同一个指针

答案 2 :(得分:1)

您的阵列太小。

#include <stdio.h>
int main(void){
double m[3][3]; // <------ Change size to 3,3
for (int i = 0 ; i<3; i++){
    for(int j=0; j<3; j++)
         printf("%p[%d][%d]     ", (void*)&m[i][j],i,j);
    printf("\n");
 }
return 0;
}

答案 3 :(得分:1)

你声明m [2] [2]有2行2,有效索引是0和1 如果你想要一个3x3数组,你必须声明

double m[3][3];