繁体   English   中英

二维数组的未定义行为分配

[英]Undefined behavior assignment of 2d array

更新:在评论中回答

将值分配给我的二维数组时,我遇到了一些奇怪的行为。 当我在 4 x 9 数组的 4 x 4 部分中分配单个值时,它工作正常,但是当我进入第 5 列及以后,多个值被更改,而不仅仅是一个。

我已经多次修改了我的复制二维数组 malloc 但问题仍然存在。 我也尝试过 memcpy,但也没有用。

int **data = (int **)malloc(4*sizeof(int*));
for(int i = 0; i < 4; i++) {
    data[i] = (int *)malloc(4*4*sizeof(int));
}
// data prints
    9 8 1 4
    2 0 5 4 
    3 0 3 2
    5 9 6 3

// copy of a 4 x 4 2d Array but adding 5 extra columns to it
int **copy = (int **)malloc(4*sizeof(int*));
for(int i = 0; i < 4; i++) {
    copy[i] = (int *)malloc(4*9*sizeof(int));
    copy[i] = data[i]; // original 2d Array
}
// copy prints
   9 8 1 4 0 0 0 0 0
   2 0 5 4 0 0 0 0 0
   3 0 3 2 0 0 0 0 0
   4 9 6 3 0 0 0 0 0

copy[0][4] = 5;

// copy prints again 
   9 8 1 4 5 0 0 0 0
   2 0 5 4 0 0 0 0 0
   3 0 3 2 0 0 0 0 0
   5 9 6 3 0 0 0 0 0

// [0][4] = 5 good but [3][0] changed from 4 to 5

free(copy);
free(data);

我期望如果我为第 5-9 列分配任何值,那么只有那个元素应该改变。

谢谢@pmg,我泄露了memory,它解决了这个问题。

暂无
暂无

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

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