释放C中的结构元素

时间:2017-11-03 16:22:24

标签: c

我有一个结构:

struct student{
    int roll_no;
    char *name = malloc(25 * sizeof(char));;
    char *phone_no = malloc(10 * sizeof(char));;
    char *dob = malloc(10 * sizeof(char));;
}*s1;

int main(){
    s1 = malloc(5 * sizeof(student)); //array of student
    //.....
}

用于分配大小的学生数组的完整循环的适当代码是什么?' n'然后取消分配? 注意:此处的问题涉及结构实例的元素的分配和解除分配。

4 个答案:

答案 0 :(得分:1)

此...

typedef struct student{
    int roll_no;    // (the following illegal syntax commented out)
    char *name;     // = malloc(25 * sizeof(char));;
    char *phone_no; // = malloc(10 * sizeof(char));;
    char *dob;      // = malloc(10 * sizeof(char));;
}*s1;

......从被描述为需要的东西(减去非法分配陈述)可能最好形成为:

typedef struct {
    int roll_no;
    char *name;    //needs memory
    char *phone;   //needs memory
    char *dob;     //needs memory
}STUDENT;          

然后,使用新变量类型:STUDENT,根据需要创建结构的实例。你的OP表明你需要5:

STUDENT s[5];     //Although this array needs no memory, the 
                  //members referenced by it do 
                  //(as indicated above)

现在,所有必要的是在5个实例的每个实例中为需要它的3个成员创建内存。

for(i=0;i<5;i++)
{
    s[i].name  = calloc(80, 1); //calloc creates AND initializes memory.
    s[i].phone = calloc(20, 1); //therefore safer than malloc IMO.
    s[i].dob   = calloc(20, 1); //Also, change values as needed to support actual
                                //length needs for name, phone and dob
}
// Use the string members of s[i] as you would any other string, But do not
// forget to free them when no longer needed.
...
for(i=0;i<5;i++)
{
    free(s[i].name);
    free(s[i].phone);
    free(s[i].dob);
}

注意,由于在此示例中创建了数组s的方式,即使用 memory on the stack instead of the heap ,因此无需释放它。

另外请注意,上面的示例代码主要关注为结构数组的char *成员创建内存的方法,但是当实际编码为keep时,[m] [c] [re]的返回在尝试使用变量之前,应该总是检查内存。例如:

s[i].name  = calloc(80, 1);
if(!s[i].name) //checking that memory was created
{
    ;//if failed, then handle error.
}
...

答案 1 :(得分:1)

除了ryyker的回答,如果你想动态地做到这一点:

#include <stdlib.h>

struct student{
    int roll_no;
    char *name;
    char *phone;
    char *dob;
};

int main()
{
    int i, student_count = 5;
    struct student ** s = malloc(sizeof(struct student *) * student_count);

    if (s)
    {
        for (i = 0; i < student_count; ++i)
        {
            s[i] = malloc(sizeof(struct student));

            if (s[i])
            {
                //set up student's members
            }
        }

        for (i = 0; i < student_count; ++i)
        {
            //free student's members before the next line.
            free(s[i]);
        }

        free(s);
    }

    return 0;
}

答案 2 :(得分:0)

您必须free malloc所有内容,并且mallocstruct内的评论中未提及#include <stdio.h> #include <stdlib.h> #define NUM_STUDENTS 5 struct student{ int roll_no; char *name; char *phone; char *dob; }; int main(void) { int i; // if this was me, I would simply replace this with // struct student s[NUM_STUDENTS];, but the goal here is to illustrate // malloc and free struct student* s = malloc(sizeof(struct student) * NUM_STUDENTS); if (s == NULL) // handle error for (i=0; i<NUM_STUDENTS; i++) { // sizeof(char) is guaranteed to be 1, so it can be left out s[i].name = malloc(25); if (s[i].name == NULL) // handle error s[i].phone = malloc(10); if (s[i].phone == NULL) // handle error s[i].dob = malloc(10); if (s[i].dob == NULL) // handle error } // do stuff with with the data .... // time to clean up, free in the reverse order from malloc for (i=0; i<NUM_STUDENTS; i++) { // the dob, phone, name order here isn't important, just make sure you // free each struct member before freeing the struct free(s[i].dob); free(s[i].phone); free(s[i].name); } // now that all the members are freed, we can safely free s free(s); return 0; }

def groupby_count(df):
    unq, t = np.unique(df.TERM, return_inverse=1)
    ids = df.ID.values
    sidx = np.lexsort([t,ids])

    ts = t[sidx]
    idss = ids[sidx]

    m0 = (idss[1:] != idss[:-1]) | (ts[1:] != ts[:-1])
    m = np.concatenate(([True], m0, [True]))
    ids_out = idss[m[:-1]]
    t_out = unq[ts[m[:-1]]]
    x_out = np.diff(np.flatnonzero(m)+1)

    out_ar = np.column_stack((ids_out, t_out, x_out))
    return pd.DataFrame(out_ar, columns = [['ID','TERM','X']])

答案 3 :(得分:0)

用户Abhijit给出了一个方向正确但不完整的答案。他的回答应该是:

typedef struct STUDENT{
    int roll_no;
    char *name;
    char *phone;
    char *dob;
}student;

void example(int n_students)
{
    student **s;
    int i;

    s= malloc(n_students * sizeof(student *));
    for (i=0; i<n_students; i++)
    {
        s[i]= malloc(sizeof(student));
        s[i]->name= malloc(25);
        s[i]->phone= malloc(10);
        s[i]->dob= malloc(10);
    }
    // now free it:
    for (i=0; i<n_students; i++)
    {
        free(s[i]->name);
        free(s[i]->phone);
        free(s[i]->dob);
        free(s[i]);
    }
    free(s);
}