首页 > 解决方案 > 增加二维数组大小后的变量变化

问题描述

一个单词被写入二维数组的第 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 被称为 Ó«

标签: c

解决方案


这里:

char* temp;
strncpy(temp, decode_structure[0], 20);

您正在使用一个未初始化的指针作为副本的目标,它调用未定义的行为 (UB)。

改为使用char temp[20];,或者如果你真的想要一个指针,然后使用 malloc 动态分配内存,这将由指针指向,如下所示char* temp = malloc(sizeof(char) * 20);


推荐阅读