如何使用malloc为C中的结构创建动态内存分配?
我想为“标题”动态分配内存,因为我不知道标题会有多长。我有以下代码:如何使用malloc为C中的结构创建动态内存分配?,c,memory-management,malloc,structure,free,C,Memory Management,Malloc,Structure,Free,我想为“标题”动态分配内存,因为我不知道标题会有多长。我有以下代码: #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;
#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;
}
}
与:
然而,它没有起作用。它说它在“=”之前需要其他东西。此外,如果标题是动态分配的,如何扫描用户输入的标题
以后如何释放内存?我假设如下:
void freememory(struct film target, n) { //n is size of structure
int i = 0;
while (i < n) {
free(target[i].title);
i += 1;
}
void freemory(结构胶片目标,n){//n是结构的大小
int i=0;
而(i
正确吗?结构部分只是一个声明,您不能在那里执行任何代码。
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
}
电影用户[n];
对于(int i=0;i结构部分只是一个声明,您不能在那里执行任何代码。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
}
电影用户[n];
对于(int i=0;我能回答我的问题吗?我能回答我的问题吗?谢谢你的回答!不过我有一些问题。正如你可能知道的,我还是C新手,我不明白你所说的微管理内存是什么意思?fgets不是用来从文件中获取内容吗?还有,因为我已经分配了内存对于大小为500(typedef struct)的标题,为什么我还要在for循环下面再次分配内存?而且,我已经试着阅读了:和,…..,但我不太明白何时使用“.”和“->”。我认为->仅用于在结构的成员是指针变量时访问该成员。但是,在学习C的动态分配部分,它还使用->从结构访问成员“int age”。或者是否可以同时使用“.”和“->”要访问任何结构成员?@WealthyPlayer这意味着在普通PC/桌面应用程序上,分配一个200字节的固定字符串还是精确分配“x”并不重要字节。fgets
用于从流中获取字符,如果您使用stdin
作为输入流,您可以从控制台获取字符。总体而言,它比scanf
更好,但在读取字符串时尤其如此。@WealthyPlayer the[500]是我的答案中的一个输入错误,很抱歉!修复了。@WealthyPlayer关于->
与
的比较,前者只是当您有指向结构的指针时访问成员的一种方便方式。编写ptr->title
比(*ptr)更具可读性.title
但它们在其他方面是等效的。谢谢你的回答!不过我有一些问题。你可能知道,我还是C新手,我不明白你所说的微管理内存是什么意思?fgets不是用来从文件中获取内容的吗?另外,因为我已经为title分配了500大小的内存(typedef struct),为什么我还要在for循环下面再次分配内存?而且,我已经试着阅读了:和,…..,但我不太明白我们何时使用“.”和“->”。我认为->仅用于在结构的成员是指针变量时访问该成员。但是,在学习C的动态分配部分,它还使用->从结构访问成员“int age”。或者是否可以同时使用“.”和“->”要访问任何结构成员?@WealthyPlayer这意味着在普通PC/桌面应用程序上,分配一个200字节的固定字符串还是精确分配“x”并不重要字节。fgets
用于从流中获取字符,如果您使用stdin
作为输入流,您可以从控制台获取字符。总体而言,它比scanf
更好,但在读取字符串时尤其如此。@WealthyPlayer the[500]是我的答案中的一个输入错误,很抱歉!修复了。@WealthyPlayer关于->
与
的比较,前者只是当您有指向结构的指针时访问成员的一种方便方式。编写ptr->title
比(*ptr).title
更具可读性,但它们在其他方面是等效的。