【发布时间】:2016-10-24 13:21:32
【问题描述】:
我想做结构体数组,但我不知道结构体数组的大小,因此我需要使用指针结构体,我想在结构体中做字符数组,我不知道字符数组的大小,因此我需要使用指针char 在这个结构中,但我不明白 malloc 和 realloc 函数。我怎样才能做到这一点 ?
#include <stdio.h>
#include <stdlib.h>
struct School{
char *school_name;
int student_size;
}*high_school;
void createSchool(struct School *s, char *schl_name, int student, int school_size)
{
int i = 0;
if(school_size == 1){
s = (struct School*) malloc(sizeof(struct School));
}
else{
s = (struct School*) realloc(s, (school_size*sizeof(struct School)));
}
(s+(school_size-1))->student_size = student;
(s+(school_size-1))->school_name = (char *) malloc(20); // 20 it is not important
(s+(school_size-1))->school_name = schl_name;
for(i; i<school_size; i++){
printf("%s\t%d\n",(s+i)->school_name, (s+i)->student_size);
}
printf("\n\n");
}
int main()
{
int i = 1;
createSchool(high_school, "Harvard", 50, i);
i++;
createSchool(high_school, "Oxford", 40, i);
i++;
createSchool(high_school, "MIT", 30, i);
}
我想做屏幕截图:
Harvard 50
Harvard 50
Oxford 40
Harvard 50
Oxford 40
MIT 30
但是程序的屏幕截图:
Harvard 50
└1q 7405760
Oxford 40
7405760
(null) 0
MIT 30
【问题讨论】:
标签: c pointers malloc structure realloc