c - 二维数组的未定义行为分配
问题描述
更新:在评论中回答
将值分配给我的二维数组时,我遇到了一些奇怪的行为。当我在 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 列分配任何值,那么只有那个元素应该改变。
解决方案
推荐阅读
- c++ - 如何访问在 C++ 类中声明的结构类型指针变量?
- javascript - 该网站如何禁用内容选择?
- javascript - 为什么显示这个错误,“,Uncaught ReferenceError: c3 is not defined”
- c - setsockopt() 不会解除绑定
- python - Convert dictionaries with list of values into a dataframe
- android - 使用 ffmpeg API 处理文件时发现无效数据
- python-3.x - 如何使用openpyxl保存共享的excel文件?
- c - 如何在C中合并两个链表
- mysql - MySQL 在连接表上应用过滤器
- php - php://output - Only output part of page and not whole page