如何使用 malloc 为 C 中的结构创建动态内存分配?
How do I create a dynamic memory allocation using malloc for structures in C?
我想为 "title" 动态分配内存,因为我不知道标题的长度。我有以下代码:
#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;
}
正确吗?
结构部分只是一个声明,你不能在那里执行任何代码。 malloc
只能在 运行 时执行。意思是你的结构应该是
typedef struct {
char* title;
int year;
int duration;
int earnings;
} film;
然后
film user[n];
for(int i=0; i<n; i++)
{
char title [200];
scanf("%s", title); // scan to temporary buffer since we don't know length
...
user[i]->title = malloc(strlen(title) + 1); // alloc just as much as is needed
}
您的 free()
代码有效。
请注意这段代码相当幼稚;像这样微管理内存在实际应用中可能不是最好的主意。选择一个固定的最大字符串长度,然后确保输入不超过它可能是一个更好的计划,方法是使用 fgets
而不是 scanf
。
我想为 "title" 动态分配内存,因为我不知道标题的长度。我有以下代码:
#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;
}
正确吗?
结构部分只是一个声明,你不能在那里执行任何代码。 malloc
只能在 运行 时执行。意思是你的结构应该是
typedef struct {
char* title;
int year;
int duration;
int earnings;
} film;
然后
film user[n];
for(int i=0; i<n; i++)
{
char title [200];
scanf("%s", title); // scan to temporary buffer since we don't know length
...
user[i]->title = malloc(strlen(title) + 1); // alloc just as much as is needed
}
您的 free()
代码有效。
请注意这段代码相当幼稚;像这样微管理内存在实际应用中可能不是最好的主意。选择一个固定的最大字符串长度,然后确保输入不超过它可能是一个更好的计划,方法是使用 fgets
而不是 scanf
。