【问题标题】:Using char in struct在结构中使用 char
【发布时间】:2013-09-22 22:48:05
【问题描述】:

我需要编写一个 c 程序来表示一个包含学生数据(姓名、分数和学号)的列表,但我不知道如何正确存储学生姓名。

我尝试使用指针,但是当我尝试分配新名称时,它会覆盖旧名称。

这是我正在使用的代码...谁能帮助我?

lista.h

typedef struct _lista lista;
typedef struct _dados dados;

typedef struct _dados{
    int matricula;
    float media;
    char *nome;
}_dados;

typedef struct _lista {
    int fim;
    dados *d[max];
}_lista;

lista* criar_lista();
dados* novo_dado(char *nome, int matricula, float media);
void imprimir(dados *dado);

lista.c

lista* criar_lista(){
    lista* L = (lista *) malloc(sizeof (lista));
    L->fim = -1;
    return L;
}

dados* novo_dado(char *nome, int matricula, float media){

    dados* d = (dados *) malloc(sizeof (dados));
    d -> matricula = matricula;
    d -> media = media;
    d -> nome = nome;
    return d;
}

void imprimir(dados *dado){
    printf("%s: ", dado->nome);
    printf("%d ", dado->matricula);
    printf("%.2f\n", dado->media);
}

ma​​in.c

lista *L1;
char nome[15];
int matricula;
float media;

L1 = criar_lista();



for (i=0;i<n;i++){
    fscanf(entrada,"%s", nome);
    fscanf(entrada,"%d", &matricula);
    fscanf(entrada,"%f", &media);
    inserir(L1,novo_dado(nome,matricula,media));

}

输入:

8
Vandre 45 7.5
Joao 32 6.8
Mariana 4 9.5
Carla 7 3.5
Jose 15 8
Fernando 18 5.5
Marcos 22 9
Felicia 1 8.5

输出:

Felicia 45 7.5
Felicia 32 6.8
Felicia 4 9.5
Felicia 7 3.5
Felicia 15 8
Felicia 18 5.5
Felicia 22 9
Felicia 1 8.5 and so on...

【问题讨论】:

  • "当我尝试分配一个新名称时,它会覆盖旧名称。" — 这就是分配通常的工作方式。你预计会发生什么?
  • 你一遍又一遍地使用同一个char nome[15]

标签: c list static struct char


【解决方案1】:

改变

d -> nome = nome;

d -> nome = strdup(nome);

这将在堆上分配一个新的 char 数组,将字符串复制到其中,并将 d-&gt;nome 设置为它的开头。因此,每个dado 都会在其自己的数组中拥有自己的nome 字符串。

在你销毁dado之前,别忘了调用free(d-&gt;nome);,否则你会出现内存泄漏。

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 2014-12-20
    • 2020-08-14
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多