When creating a single pointer array for representing a 2D array, what is the size of the pointer array? Is it row or column of the 2D array?

huangapple go评论67阅读模式
英文:

When creating a single pointer array for representing a 2D array, what is the size of the pointer array? Is it row or column of the 2D array?

问题

这段代码是我的老师给的,它运行正常,但我对为什么是 int (*x1)[3]; 而不是 int (*x1)[2];Feeling confused,因为 y 只有2行。我认为这个数组 x1 的每个元素将存储到 y 的行的地址,所以只需要两个这样的元素,而不是3个。请帮我解释一下。谢谢

int main(){
int (*x1)[3];
int y[2][3]={{1,2,3},{4,5,6}};
x1 = y;
for (int i = 0; i<2; i++)
  for (int j = 0; j<3; j++)
    printf("\n The X1 is %d and Y is %d",*(*(x1+i)+j), y[i][j]);
return 0;
}

我尝试运行了这段代码,它运行正常。但我不明白它是如何工作的。内部发生了什么?内存是如何分配的?

英文:

So, this code was given by my teacher and it works fine, but I am confused as to why it is int (*x1)[3]; and not int (*x1)[2]; as y has 2 rows only. I think that each element of this array x1 will store the address to the row of y so only two such elements are required and not 3. Kindly help me. Thank you

int main(){
int (*x1)[3];
int y[2][3]={{1,2,3},{4,5,6}};
x1 = y;
for (int i = 0; i<2; i++)
  for (int j = 0; j<3; j++)
    printf("\n The X1 is %d and Y is %d",*(*(x1+i)+j), y[i][j]);
return 0;
}

I tried running this code and it is working fine. I don't understand how it is working though. Like what is going on internally? How is the memory being allocated?

答案1

得分: 1

int y[2][3]={{1,2,3},{4,5,6}};
每个`y`中的元素都是`int[3]`,`y`有2个这样的元素。这声明了一个指向这种元素的指针:
int (*x1)[3];
而在这里,`y`会衰减为指向第一个元素的指针,这就是为什么赋值有效的原因:
x1 = y;

建议稍微修改以使其更容易阅读:

x1 = y;
for (int i = 0; i < 2; ++i, ++x1) // 在这里步进 x1
    for (int j = 0; j < 3; ++j)
        printf("\n X1 是 %d 而 Y 是 %d", (*x1)[j], y[i][j]);
// 并且在这里对其进行解引用变得更加清晰 ^^^^^^^^
英文:
int y[2][3]={{1,2,3},{4,5,6}};

Every element in y is an int[3] and y has 2 such elements. This declares a pointer to one such element:

int (*x1)[3];

And in this, y decays into a pointer to the first element which is why the assignment works:

x1 = y;

Suggestion for making it a little easier to read:

x1 = y;
for (int i = 0; i &lt; 2; ++i, ++x1) // step x1 here
    for (int j = 0; j &lt; 3; ++j)
        printf(&quot;\n The X1 is %d and Y is %d&quot;, (*x1)[j], y[i][j]);
// and dereferencing it becomes nicer here    ^^^^^^^^

huangapple
  • 本文由 发表于 2023年6月19日 03:10:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定