【发布时间】:2013-02-23 19:48:10
【问题描述】:
简单来说,我声明了一个结构体:
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);
【问题讨论】:
-
but I get an error- 你得到什么错误? (我很想链接到toomuchcode.org/2008/11/guru-myth.html :-)) -
抱歉没有具体说明。我在 Xcode 中得到“EXC_BAD_ACCESS (code =1, address = 0 x 0)。我也尝试在其他编译器中运行此代码,但它也失败了。
-
您可以共享文件中的数据吗?您似乎在格式说明符中缺少“\n”或其他一些字符,请尝试逐一阅读每个条目,您将了解您缺少什么
-
如果你的字段是固定长度的,为什么不在结构中使用数组语法?它会给出相同的最终结果,但使用更少的代码和内存。
-
为什么
count是一个指针?为什么(*count)++;?
标签: c arrays pointers struct increment