我一直在尝试完成此代码,但我一直坚持创建临时缓冲区。我以前从未学过,但是我需要以某种方式将其用于程序。
在这个网站上,我认为最好的选择是
char * func1() {
char *buffer = (char *)malloc(1000);
buffer[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.nn", lunch[x].name, lunch[x].weight, lunch[x].calories);
free(lunch[x].name);
}
return 0;
}
首先,它是 for(x = ARRAY; x < LUNCHES; ++x)
-注意<
而不是<=
,否则您将溢出数组(索引基于零,它从0
运行到LUNCHES-1
)。
至于分配:
- 您需要为
lunch[]
数组中的每个条目创建缓冲区,因此在for循环中,您需要诸如lunch[x].name = malloc(SIZE)
之类的东西,其中SIZE
是一个合理的值 - 为了用餐名称,〜80个字符似乎远远足够; <<<<<<<<<<<<<</li> - 接下来您必须才能检查,分配给
lunch[x].name
的指针不是NULL
,它会发出记忆条件的信号 - 否则,您可能碰巧可以通过解释; - 然后,您可以将指针(新分配的缓冲区)用作
scanf()
的参数,但请记住指定最大宽度(即SIZE-1
),以便您不要将其倒入未分配的内存中。
请记住,当您不再需要数据或在程序结束时,在指示器上使用free()
分配内存 - 虽然在您的简单示例中,从技术上讲,这是没有必要的,但它很容易开始一个非常坏的习惯。