C 如何设置动态内存和临时缓冲区?
我一直在试图完成这段代码,但我一直在创建一个临时缓冲区。我以前从未学过这一点,但不知何故,我需要在我的程序中使用它 从我看来,最好的选择是C 如何设置动态内存和临时缓冲区?,c,memory,dynamic,malloc,C,Memory,Dynamic,Malloc,我一直在试图完成这段代码,但我一直在创建一个临时缓冲区。我以前从未学过这一点,但不知何故,我需要在我的程序中使用它 从我看来,最好的选择是 char * func1() { char *buffer = (char *)malloc(1000); buffer[0] = '\0'; // Initialize buffer // Do processing to fill buffer return buffer; } 下面是我的代码 #include
char * func1() {
char *buffer = (char *)malloc(1000);
buffer[0] = '\0'; // Initialize buffer
// Do processing to fill buffer
return buffer;
}
下面是我的代码
#include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
#define ARRAY 2
int main(void)
{
int x;
struct Food
{
char *name; /* “name” attribute of food */
int weight, calories; /* “weight” and “calories” attributes of food */
}lunch[LUNCHES] = { [0] = {"apple", 4, 100}, [1] = {"salad", 2, 80} };
for(x = ARRAY; x < LUNCHES; ++x)
{
char *buff = malloc(sizeof(lunch[x].name));
printf("Please input \"food\", weight, calories: ");
scanf("%s", buff);
scanf("%d %d", &lunch[x].weight, &lunch[x].calories);
printf("The %s weighs %doz. and contains %d calories.\n", lunch[x].name, lunch[x].weight, lunch[x].calories);
}
return 0;
}
好的,我改了。但现在输出是
空值加权并包含。为什么为空
纠正
#include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
#define ARRAY 2
int main(void)
{
int x;
struct Food
{
char *name; /* “name” attribute of food */
int weight, calories; /* “weight” and “calories” attributes of food */
}lunch[LUNCHES] = { [0] = {"apple", 4, 100}, [1] = {"salad", 2, 80} };
for(x = ARRAY; x < LUNCHES; x++)
{
lunch[x].name = malloc(25 * sizeof(char));
printf("Please input \"food\", weight, calories: ");
scanf("%s", lunch[x].name);
scanf("%d %d", &lunch[x].weight, &lunch[x].calories);
printf("The %s weighs %doz. and contains %d calories.\n\n", lunch[x].name, lunch[x].weight, lunch[x].calories);
free(lunch[x].name);
}
return 0;
}
首先,它是forx=ARRAY;午餐++注意,不,这不对,你真的需要再看看for循环。好的。你需要说午餐[x].name=malloc952;,然后扫描%951s,午餐[x].name。我必须分配内存大小吗?因为我想让程序计算出要使用多少。程序应该如何做到这一点?你正在使用用户输入的缓冲区。您如何知道用户将键入多少内容?你应该分配一个合理的大小,然后在你的scanf格式字符串中使用这个大小,以确保你读的内容不会超过这个。我知道免费的。我只是还没说到那一点。谢谢。难道不能让程序根据餐名字符串的大小计算出要使用多少内存吗?当然,如果你知道要使用多少项的话。但问题是,为什么不直接将数组放入结构中,就像在struct Food{char name[NAMELEN];…}