c - 增加二维数组大小后的变量变化
问题描述
一个单词被写入二维数组的第 0 行和第 0 列。当我去调整数组大小以准备存储另一个单词时,我将第 0 行和第 0 列的单词存储到临时变量中。在我调用增加二维数组大小的函数后,临时变量变成了非常奇怪的东西。例如,我传入了“i”,在增加行的大小后,存储 i 的变量 temp 发生了变化。为什么会这样?
void make_row_decode_structure_bigger(int rows){
printf("inside the making the rows bigger \n");
int max_rows = rows+1;
char **store = realloc( decode_structure, sizeof *decode_structure * (rows + 2) );
printf("after a store has been assigned\n");
if (store){
decode_structure = store;
for(size_t i = 0; i < 2; i++ ){
decode_structure[rows + i] = calloc(20, sizeof(char));
}
}
printf("end of making the rows increase\n");
return;
//decode_structure[max_rows][0] = '\0';
}
//other part of code
char* temp;
strncpy(temp, decode_structure[0], 20);
printf("this word %s is at the top of decode_structure\n", temp);
printf("make the rows bigger is being called\n");
make_row_decode_structure_bigger(num);
printf("temp after make_row_decode_structure_biggeris called %s \n", temp);
这是输出:
这个词 i 在 decode_structure 的顶部 使行更大在内部被调用 在分配存储后使行更大 在 make_row_decode_structure_bigger 之后使行增加 temp 被称为 Ó«
解决方案
这里:
char* temp;
strncpy(temp, decode_structure[0], 20);
您正在使用一个未初始化的指针作为副本的目标,它调用未定义的行为 (UB)。
改为使用char temp[20];
,或者如果你真的想要一个指针,然后使用 malloc 动态分配内存,这将由指针指向,如下所示char* temp = malloc(sizeof(char) * 20);
:
推荐阅读
- database - 具有排他锁性能问题的 Postgres 选择查询
- javascript - 如何从 javascript 中具有重复属性的 HTML 文档中获取数组?
- django - 与鹡鸰标签相关的附加字段?
- iot - 逻辑转换器必须与面包板一起使用吗?
- python - 函数调用之间的递归函数中的持久参数
- debugging - 用于 Linux 内核的单独调试符号文件
- python - 高斯核的值(系数)是多少?
- javascript - 箭头函数中的“this”未显示词法范围
- docker - 从 Docker Image 在 OpenShift 中安装 Jenkins
- python - docker-compose:sqlalchemy.exc.ArgumentError:无法从字符串解析 rfc1738 URL