我很难获得指向结构的指针数组来保存和检索我填充的数据,代码片段是我程序的核心。
我能够使用结构数组使程序本身工作,但我认为这会占用更多内存,并且我试图只重新分配指向结构的指针数组,而不是每个循环中的所有结构。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dados_aluno {
int matricula;
char nome[60];
int situacao;
float nota1, nota2, nota3, media;
}dados_aluno;
int main(void){
int done = 0;
int i;
int n_alunos = 0;
int matricula_atual;
dados_aluno *novo_aluno;
dados_aluno **alunos_da_turma;
alunos_da_turma = malloc(sizeof(dados_aluno*));
while (done == 0){
printf("Matricula: ");
scanf("%d", &matricula_atual);
fflush(stdin);//scanf followed by gets = bad time!
if (matricula_atual == -1){
done = 1;
continue;
}
n_alunos++;
novo_aluno = calloc(1, sizeof(dados_aluno));
novo_aluno->matricula = matricula_atual;
printf("\nNome: ");
gets(novo_aluno->nome);
//the code below rises warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
//and returns garbage on the for loop at the end of the program
alunos_da_turma[n_alunos - 1] = &novo_aluno;
//using memcpy instead doesnt rise an error, but the first field is garbage and the 3º interation of the loop crashes
//memcpy(alunos_da_turma[n_alunos -1],&novo_aluno,sizeof(dados_aluno *));
alunos_da_turma = realloc(alunos_da_turma, (sizeof(dados_aluno *) * (n_alunos + 1)));
}
for (i=0;i<(n_alunos);i++){
printf("%d %s\n",alunos_da_turma[i]->matricula,alunos_da_turma[i]->nome);
}
}
我希望动态分配一个结构“dados_alunos”并动态分配一个指向所述结构的指针数组,将用户输入“nome”和“matricula_atual”插入结构“dados_alunos”的字段并能够读取它们退出 while 循环后。 尝试使用
将当前结构的地址保存到数组中alunos_da_turma[n_alunos - 1] = &novo_aluno;
发出警告“来自不兼容的指针类型 [-Wincompatible-pointer-types] 的赋值”并且似乎将第一个指针/垃圾写入数组的所有位置,无论有多少交互。 如果我只尝试一次交互并在 while 循环中在 2 次或更多次交互中崩溃,则使用 memcpy 代替将垃圾存储在第一个字段上。
最佳答案
alunos_da_turma[n_alunos - 1] = &novo_aluno;
被拒绝,因为 alunos_da_turma
是一个 dados_aluno **
所以 alunos_da_turma[n_alunos - 1]
是一个 dados_aluno *
>,但是 novo_aluno
是一个 dados_aluno *
所以 &novo_aluno
是一个 dados_aluno **
你想要
alunos_da_turma[n_alunos - 1] = novo_aluno;
警告
gets(novo_aluno->nome);
是危险的(并且多年来已被弃用),因为如果输入字符串大于 59 个字符,您会以意外行为从字段中写出,执行
fgets(novo_aluno->nome, sizeof(novo_aluno->nome), stdin);
但是,除非您在输入 matricula 的同一行输入名称,否则您将得到一个空行,因为该行/换行符的其余部分未被 fflush(stdin);
刷新,< em>fflush 无法处理文件
如果名称不能包含分隔符,请使用 scanf("%59s", novo_aluno->nome);
而不是 fgets,否则明确地绕过字符直到换行符
注意也在
alunos_da_turma = realloc(alunos_da_turma, (sizeof(dados_aluno *) * (n_alunos + 1)));
你重新分配了一个额外的元素,你已经增加了n_alunos
做
int done = 0;
...
while (done == 0){
...
if (matricula_atual == -1){
done = 1;
continue;
}
...
}
其实很复杂,可以用
代替for (;;) {
...
if (matricula_atual == -1)
break;
...
}
关于c - 将指向结构的指针保存到指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094471/