提问人:Saarthak 提问时间:3/17/2021 更新时间:3/17/2021 访问量:39
使用 malloc 为结构分配无法正常工作的内存
Memory allocation using malloc for structures not working properly
问:
struct student* addStudent(struct student* list, int* length){
struct student* newList = malloc(sizeof(list)*(*length+1));
for (int i=0; i<*length; i++){
strcpy(newList[i].name, list[i].name);
strcpy(newList[i].rollNumber, list[i].rollNumber);
strcpy(newList[i].class, list[i].class);
};
//Adding some data in the added element
free(list);
(*length)++;
return newList;
}
void main(){
struct student* list = malloc(sizeof(struct student));
struct student** ptrToList = &list;
strcpy(list[0].name, "");
strcpy(list[0].rollNumber, "");
strcpy(list[0].class, "");
int length = 1;
while (1){
printOptions();
int option;
printf("Your pick: ");
scanf("%d", &option);
newLn();
switch(option){
case 1:
*ptrToList = addStudent(*ptrToList, &length);
我遇到的问题是,当 while 循环运行时,案例 1 第一次运行并且我能够添加数据,并且在随后的迭代中,我也能够使用 *ptrToList 访问该数据,但是每当我尝试再次运行案例 1 时,程序就会结束。为什么会这样?
答: 暂无答案
评论
list
是一个指针,所以当你这样做时,你得到的是指针的大小,而不是被指向的类型的大小。sizeof(list)
sizeof(struct student)
sizeof(*newList)
sizeof(struct student)
realloc
struct student * addStudent(struct student *list, int *length) { list = realloc(list,sizeof(*list) * (*length + 1)); struct student *cur = &list[*length++]; return list; }