简单来说,我声明了一个结构:
typedef struct
{
char* studentID;
char* studentName;
int* studentScores;
}STUDENT;
然后我声明了一个指针并为指针和每个元素分配了内存:
STUDENT* studentPtr = NULL;
if ((studentPtr = (STUDENT*) calloc (5, sizeof(STUDENT))) == NULL)
{
printf("Not enough memory\n");
exit(100);
}
{
if ((studentPtr->studentID = (char*) calloc (20, sizeof(char))) == NULL)
{
printf("Not enough memory\n");
exit(100);
}
if ((studentPtr->studentName = (char*) calloc (21, sizeof(char))) == NULL)
{
printf("Not enough memory\n");
exit(100);
}
if ((studentPtr->studentScores = (int*) calloc (5, sizeof(int))) == NULL)
{
printf("Not enough memory\n");
exit(100);
}
之后,我想从文件中读取 5 条记录,但由于我的增量,当我尝试运行程序时出现错误。(如果我有类似“char studentName[20];”之类的东西,它工作得很好)我应该如何增加指针以达到我想要的结果?它必须采用指针表示法。
STUDENT* ptr = studentPtr;
while (*count < MAX_SIZE)
{
fscanf(spData, "%s %*s %*s %*d %*d %*d %*d %*d", ptr->studentName)
(*count)++;
ptr++;
}
File Content:
Julie Adams 1234 52 7 100 78 34
Harry Smith 2134 90 36 90 77 30
Tuan Nguyen 3124 100 45 20 90 70
Jorge Gonzales 4532 11 17 81 32 77
Amanda Trapp 5678 20 12 45 78 34
最后一个问题:如果我保留声明的结构并为其正确分配内存。完成后如何释放它?应该是这样的吗?
for (STUDENT* ptr = studentPtr; ptr < studentPtr + *count; ptr++)
{ //*count is the number of records
free(ptr->studentID);
free(ptr->studentName);
free(ptr->studentScores);
}
free(studentPtr);