C - 函数中的结构分配

时间:2014-08-19 14:27:22

标签: c function memory-management struct

我试图在函数内部分配一个struct数组,但是当我返回main时,它就像我刚刚分配的内存一样被覆盖了。这是我的示例代码:

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

struct Class {
  int students;
  Person * N;
};

struct Person
{
  char * name;
  int age;
};

void allocation(struct Class ** myclasspointer)
{
    struct Class *mytempstruct= malloc(sizeof *mytempstruct); 
    mytempstruct -> students = 10;
    char *n= "My name is...?";

    mytempstruct -> N = malloc (sizeof (mytempstruct -> N) * 10);
    for (i = 0; i < 10; i++) {
        mytempstruct -> N[i].age = i;
        mytempstruct -> N[i].name = malloc (sizeof (char) * (strlen(n));
        strncpy (N[i].name, n, strlen(n));
    }

    *myclasspointer = mytempstruct;
}

int main(void)
{
  int i;
  struct class * MyClass;

  allocation(&MyClass);

  for (int i = 0; i < MyClass.students; i++)
     Prinf("Student %s, age %d: %d \n",  MyClass->N[i].name, MyClass->N[i].age);

  for (int i = 0; i < MyClass->students; i++)
     free(MyClass->N[i]);
  free (MyClass);

  return 0;
}

一旦我回到主要,只有一些值是他们应该的。我也试着改变:

void allocation(struct Class ** myclasspointer)
{
    struct Class *mytempstruct= malloc(sizeof *mytempstruct); 

    char *n= "My name is...?";

    mytempstruct -> N = malloc (sizeof (mytempstruct -> N) * 10);
    for (i = 0; i < 10; i++) {
        mytempstruct -> N[i].age = i;
        mytempstruct -> N[i].name = malloc (sizeof (char) * (strlen(n));
    }

    *myclasspointer = mytempstruct;
}

为:

void allocation(struct Class ** myclasspointer)
{
    myclasspointer= malloc(sizeof *myclasspointer); 

    char *n= "My name is...?";

    myclasspointer-> N = malloc (sizeof (myclasspointer-> N) * 10);
    for (i = 0; i < 10; i++) {
        mytempstruct -> N[i].age = i;
        mytempstruct -> N[i].name = malloc (sizeof (char) * (strlen(n));
    }
}

但我有同样的结果。

2 个答案:

答案 0 :(得分:1)

首先,您需要person的前瞻性声明。然后改变

mytempstruct -> N = malloc (sizeof (mytempstruct -> N) * 10);  
                                   ^will give the size of pointer instead of structure `person`  

mytempstruct -> N = malloc (sizeof (struct person) * 10);

答案 1 :(得分:1)

    mytempstruct -> N[i].name = malloc (sizeof (char) * (strlen(n)) );
    strncpy (N[i].name, n, strlen(n));

你想错了:

    mytempstruct -> N[i].name = malloc (sizeof (char) * (strlen(n)+1) );
    strncpy (N[i].name, n, strlen(n)+1);

表示空字符的空格。