首页 > 解决方案 > C String 数组中的每个值都等于最后添加的值

问题描述

我正在尝试使用文本行分析数据文件,然后使用 while 循环将文本行添加到字符串数组中。似乎每次我在索引处向数组添加新行时,索引中低于它的每个值都设置为正在添加的字符串。例如,如果我将 strings[2] 设置为值“foo”,它也会将 strings[1] 和 strings[0] 设置为“foo”,即使 strings[1] 和 strings[0] 的值不同前。

我尝试过测试,看看我添加到数组中的值是正确的,而且它们是正确的。我也尝试过将数组设为 const,但没有成功。

int main()
{
    char** strings = malloc(1000 * sizeof(char));
    int index = 0;
    StringBundle** bundle = malloc(1000 * sizeof(StringBundle)); //StringBundle is used to parse the string

    while (fgets(str, 500, file))
    {
        bundle[index] = createStringBundle(str); //String bundle works correctly
        char** tokens = bundle[index]->Tokens; //Gets the parts of a parsed string
        char concat[100]; //This string is composed of two parts of the string that is parsed
        strcpy(concat, tokens[1]);
        strcat(concat, tokens[3]);
        printf("%s\n", concat) //This will print the correct value, so the value of concat is correct
        strings[index] = concat;
        index++;
    }
    //"Montery CA" is the last value added to the array
    printf("%s\n", strings[2]); //Issue- this will print "Montery CA", when it should print "Chicago IL"
    printf("%s\n", strings[13]); //Issue- this will print "Montery CA", when it should print "San Diego CA"
}

标签: carrays

解决方案


推荐阅读