使用 excel 值的指针和结构在 C 中显示问题

Display issue in C with pointer and structur from excel values

我在 运行 我的程序时遇到问题。事实上,我无法正确显示从我的 excel 文件(使用 UTF-8 正确编码)中获取的每个变量。此 excel 文件仅包含城市名称。这些名称存储在我的指针列表中的结构(此处测试)中,名为:"test_list"。但是,当我之前显示这些变量时,它们显示正确。

请参阅下面我的简化程序和输出:

#include <stdio.h>
#include <stdlib.h>

typedef struct Test Test;

const nbr_villes = 23;

struct Test
{
    char* nom;
};

Test *init_test(char *nom) {

    Test *test = malloc(sizeof(Test));
    test->nom = nom;

    return test;
}

void fill_test(Test **test_list)
{
    FILE *csv_file = fopen("villes.csv", "r");

    char line[1024];

    // remove header "Ville"
    fgets(line, 0, csv_file);

    for (int i = 0 ; i < nbr_villes ; i++)
    {
        fgets(line, 1024, csv_file);
        char *tmp = strdup(line);
        printf("%s\n", tmp);
        test_list[i] = init_test(tmp);
        free(tmp);
    }
}

int main()
{
    // 23 éléments dans liste de test
    Test **test_list = malloc(nbr_villes * sizeof(struct Test));
    fill_test(test_list);

    for (int i = 0; i < nbr_villes; i++){
        printf("%s\n",test_list[i]->nom);
    }
}

和输出:

(prints of tmp :)

ville

Amiens

Bayonne

Bordeaux

Bourges

Caen

Clermont-Ferrand

Dijon

Grenoble

Le-Mans

Lille

Lyon

Marseille

Metz

Montpellier

Nantes

Nice

Niort

Paris

Reims

Rennes

Strasbourg

Toulouse

(Errors are here : prints in the main loop :)

@f
@f
êf
êf
êf
êf
¿f
¿f
░f
░f
░f
░f
░f
Metz

░f
Rennes

Ïf
Niort

pf
hf
Rennes

Strasbourg

Toulouse

感谢您的帮助。

    char *tmp = strdup(line);
    printf("%s\n", tmp);
    test_list[i] = init_test(tmp);
    free(tmp);

char * 记忆的 int Test 本身记忆在 test_listfree(tmp)

test->nom = nom;复制指针,字符串不重复,需要做test->nom = strdup(nom);或者直接去掉free(tmp);

但对我来说最好的方法是调用 init_test(line)(不重复)并且 strdup 是在 init_test 中生成的,因为它必须知道一个必须进行复制,而不是调用者