我想將學生的記錄存儲在名爲student的指針變量中。 我將指針變量聲明爲結構student_info的類型,如代碼中所示,並且只要我們想輸入學生記錄就使用malloc將內存分配給student變量。我想訪問第i個學生並嘗試輸入該值。我試圖使用下面的代碼訪問ith元素,但它不能正常工作。每當我嘗試打印存儲在學生變量中的值時,它總是顯示零。請告訴我這段代碼中的錯誤,並且是我訪問元素的方式是否正確。如何獲取指定爲結構類型的指針變量的值
#include<stdio.h>
#include<stdlib.h>
int i;
struct student_info
{
int id;
char name[20];
int quiz1;
int quiz2;
int total_score;
};
int choice();
int add_record(struct student_info *);
int main()
{
int option;
struct student_info *student;
student = (struct student_info *) malloc(sizeof(struct student_info));
while (1)
{
option = choice();
if (option == 1)
{
add_record(student);
}
else
{
exit(0);
}
}
return 0;
}
int choice()
{
int option;
printf("------------------------------------\n");
printf("------------------------------------\n");
printf("\t\tMenu\t\t\n");
printf("------------------------------------\n");
printf("------------------------------------\n");
printf("1. Add student record\n");
printf("0. exit\n")
printf("Enter your choice\n");
scanf("%d", &option);
return option;
}
int add_record(struct student_info * student)
{
if (i != 0)
{
student = (struct student_info *) malloc(sizeof(struct student_info) * (i + 1));
}
(student + i)->id = i;
printf("enter student name");
scanf("%s", (student + i)->name);
printf("Enter quiz 1 marks");
scanf("%d", &(student + i)->quiz1);
printf("Enter quiz 2 marks");
scanf("%d", &(student + i)->quiz2);
(student+i)->total_score = (student +i)->quiz1 + (student+i)->quiz2;
i++;
printf("Total_score %d\n", *&(student + i)->total_score);
return 0;
}
'int add_record(struct student_info ** student)'並使用'realloc'而不是'malloc'。 – BLUEPIXY 2014-10-27 14:40:48
[如何在C中使用realloc函數]的可能的重複(http://stackoverflow.com/questions/13748338/how-to-use-realloc-in-a-function-in-c) – 2014-10-27 14:42:33
@ n.m。我認爲這個問題是完全不同的。這完全是關於realloc。 – user3860949 2014-10-27 15:46:55