我一直在尝试完成这段代码,但我一直在创建一个临时缓冲区。我以前从未学过这个,但不知何故我需要在我的程序中使用它。
从这个网站我认为最好的选择是
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;
}