通过引用传递结构将动态创建和填充结构数组的函数

时间:2018-01-16 05:39:12

标签: c arrays pointers data-structures

我想将结构指针传递给一个函数,该函数将在传递的结构指针指向的位置动态创建结构数组。我能够成功地创建和填充结构数组,但是当尝试使用传递的指针在调用函数中打印数据时,会给我一个垃圾值。请帮助我知道为什么我的结构指针指向垃圾,以及如何正确访问我的数据。

以下是一些示例代码,用于演示如何使用malloc&传递和动态填充结构。 realloc的。这是INCORRECT方法:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student 
{
    int id;
    char name[20];
    float percentage;
};

void func(struct student *record);

int main() 
{
    struct student *record = NULL;

    record = (struct student *)malloc(sizeof(struct student));

    func(record);

    if(record != NULL)
    {
        for(int i=0; i<2; i++)
        {
            printf(" 1 Id is: %d \n", record[i].id);
            printf(" 1 Name is: %s \n", record[i].name);
            printf(" 1 Percentage is: %f \n", record[i].percentage);
            printf("\n");
        }
    }
    else
    {
        printf("record pointer is null");
    }

    return 0;
}

void func(struct student *record1)
{
    for(int i=0; i<2; i++)
    {
        if(i)
        {
            record1 = (struct student *)realloc(record1,sizeof(struct student)*(i+1));
        }
        record1[i].id=1;
        strcpy(record1[i].name, "Raju");
        record1[i].percentage = 86.5;
    }
}

以下是使用双指针的类似示例,这是执行此操作的正确方法:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student 
{
    int id;
    char name[20];
    float percentage;
};

void func(struct student **record);

int main() 
{
    struct student *record = NULL;

    func(&record);

    if(record != NULL)
    {
        for(int i=0; i<2; i++)
        {
            printf(" 1 Id is: %d \n", record[i].id);
            printf(" 1 Name is: %s \n", record[i].name);
            printf(" 1 Percentage is: %f \n", record[i].percentage);
            printf("\n");
        }
    }
    else
    {
        printf("record pointer is null");
    }

    free(record);

    return 0;
}

void func(struct student **record1)
{
    *record1 = (struct student *)malloc(sizeof(struct student));
    for(int i=0; i<2; i++)
    {
        if(i)
        {
            *record1 = (struct student *)realloc(*record1,sizeof(struct student)*(i+1));
        }
        (*record1)[i].id=1;
        strcpy((*record1)[i].name, "Raju");
        (*record1)[i].percentage = 86.5;
    }
}

1 个答案:

答案 0 :(得分:1)

您的第一个解决方案,

record1 = (struct student *)realloc(record1,sizeof(struct student)*(i+1));
只要realloc不必移动指针,

就可以工作也就是说,realloc只是扩展它之前给record1的内存区域。在稍后的某个阶段,realloc应该要求给你另一段记忆,那么record中的早期指针main将变为无效,现在可以包含你的&#34;垃圾&#34;。

正如您所想,您需要一个双指针才能在main中看到更改的指针。你快到了,只是一个错字:

*record1 = (struct student *)realloc(record1,sizeof(struct student)*(i+1));

在上一行中,第二次出现record1也必须取消引用,因此*record1因为您必须给realloc原始指针。

哦,没有施放malloc的结果!虽然编译器没有抱怨,但它可能会导致未来的问题。