【发布时间】:2018-11-08 08:39:45
【问题描述】:
我想动态地为“标题”分配内存,因为我不知道标题会有多长时间。我有以下代码:
#include<stdio.h>
#include<malloc.h>
struct film {
char title[500];
int year;
int duration;
int earnings;
};
void main() {
int n;
scanf("%d", &n);
int array[n], i = 0;
struct film user[n];
while (i < n) {
scanf("%s", &user[i].title);
scanf("%d", &user[i].year);
scanf("%d", &user[i].duration);
scanf("%d", &user[i].earnings);
i += 1;
}
}
我尝试替换:
char title[500];
与:
char *title = (char*)malloc(sizeof(char));
但是,它没有用。它说它在“=”之前需要其他东西。另外,如果标题是动态分配的,我如何扫描用户的输入?
以后如何释放内存?我假设它如下:
void freememory(struct film target, n) { //n is size of structure
int i = 0;
while (i < n) {
free(target[i].title);
i += 1;
}
正确吗?
【问题讨论】:
-
有人可以回答我的问题吗?
标签: c memory-management malloc structure free