简体   繁体   English

在结构中使用char

[英]Using char in struct

I need to make ac program to represent a list with students data (name, score and student number) but I can't figure out how to correctly store the students names. 我需要制作一个ac程序来代表带有学生数据(姓名,分数和学生编号)的列表,但我不知道如何正确存储学生姓名。

I tried to use pointer but when I try to assign a new name, it overwrites the old one. 我尝试使用指针,但是当我尝试分配新名称时,它将覆盖旧名称。

Here is the code I'm using...can anyone help me? 这是我正在使用的代码...有人可以帮助我吗?

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 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));

}

input: 输入:

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

output: 输出:

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...

Change 更改

d -> nome = nome;

to

d -> nome = strdup(nome);

This will allocate a new char array on the heap, copy the string to it, and set d->nome to the start of it. 这将在堆上分配一个新的char数组,将字符串复制到其中,并将d->nome设置为它的开始。 Thus each dado will have its own nome string in its own array. 因此,每个dado将在其自己的数组中具有自己的nome字符串。

Just before you destroy a dado , don't forget to call free(d->nome); 就在销毁一个dado之前,别忘了打电话给free(d->nome); , otherwise you have a memory leak. ,否则会发生内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM