0
我需要制作一个c程序来表示包含学生数据(姓名,分数和学号)的列表,但我无法弄清楚如何正确存储学生姓名。在结构中使用char
我试图使用指针,但当我尝试分配一个新名称时,它会覆盖旧的名称。
这是我使用的代码...任何人都可以帮助我吗?
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);
}
的main.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]'。 – lurker