首页 > 解决方案 > 二维数组的未定义行为分配

问题描述

更新:在评论中回答

将值分配给我的二维数组时,我遇到了一些奇怪的行为。当我在 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 列分配任何值,那么只有那个元素应该改变。

标签: cundefined-behavior

解决方案


推荐阅读