增加指向struct的指针

时间:2013-03-08 09:50:36

标签: c arrays pointers struct increment

简而言之,我已经宣布了一个结构:

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

2 个答案:

答案 0 :(得分:2)

问题是你只为studentPtr [0]中的字段分配了内存。表a中的其余四个条目仍为零。

试试这个:

int i;
for (i = 0; i < 5; i++)
{
    if ((studentPtr[i]->studentID = (char*) calloc (20, sizeof(char))) == NULL)
    {
        printf("Not enough memory\n");
        exit(100);
    }

    if ((studentPtr[i]->studentName = (char*) calloc (21, sizeof(char))) == NULL)
    {
        printf("Not enough memory\n");
        exit(100);
    }
    if ((studentPtr[i]->studentScores = (int*) calloc (5, sizeof(int))) == NULL)
    {
        printf("Not enough memory\n");
        exit(100);
    }
}

事实上,通过为各个字段使用动态分配的内存,您将使自己的生活更加艰难。您不仅需要明确地分配每个字段(并且可能在以后释放它们),这会花费代码和时间,您还会在堆表中产生额外的内存开销。如果字段是可变大小,但是它们是固定大小的,那么这是必要的,因此直接数组效率更高。

所以,我最终得到了这个:

typedef struct
{
  char studentID[20];
  char studentName[21];
  int studentScores[5];
} STUDENT;

STUDENT studentPtr[5];

答案 1 :(得分:1)

首先,你只是将内存分配给结构的指针5倍而不是结构的内存。

再次在同一行上,您只从已分配的内容(5个结构)为第一个结构分配内存。

你应该做5次,因为你有5个结构,如:

for (i = 0; i < 5; i++)
{
//Do assignments to each element in structure not more than required
//as you are doing in your code:
studentPtr[i]->studentScores = (int*) calloc(5,sizeof(int))
//so your assignment of memory should be:
studentPtr[i]->studentScores = (int*) calloc(sizeof(int))
}