【发布时间】:2012-11-12 21:45:12
【问题描述】:
我一直在尝试完成这段代码,但我一直在创建一个临时缓冲区。我以前从未学过这个,但不知何故我需要在我的程序中使用它。
来自this website我认为最好的选择是
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;
}
好的,改变了这一点。但是现在的输出是
NULL 称重并包含 .为什么为空?
更正
#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;
}
【问题讨论】:
-
不,这是不对的,你真的需要再看一遍
for循环。 -
好的。你需要说
lunch[x].name = malloc(952);,然后说scanf("%951s", lunch[x].name)。 -
我必须分配内存大小吗?因为我想让程序弄清楚要使用多少。
-
程序应该如何做到这一点?
-
您正在使用缓冲区进行用户输入。你怎么知道用户会输入多少?您应该分配一个合理的大小,然后在您的
scanf格式字符串中使用这个大小,以确保您不会阅读更多内容。