我一直在试图完成这段代码,但我被困在创建一个临时缓冲区。我以前从未学过这个,但不知怎么的,我需要用它来做我的程序。
我认为最好的选择是

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;
}

最佳答案

首先,它是for(x = ARRAY; x < LUNCHES; ++x)-注意<而不是<=,否则会溢出数组(索引是基于零的,它从0运行到LUNCHES-1)。
至于分配:
您需要为lunch[]数组中的每个条目创建缓冲区,因此在for循环中,您需要类似lunch[x].name = malloc(SIZE)的内容,其中SIZE是一个合理的值-对于餐名而言,80个字符似乎已经足够了;
接下来,您必须检查分配给lunch[x].name的指针是否不是NULL,这将发出内存不足的信号-否则,您可能会通过取消对它的引用而导致分段错误;
然后,可以将指针(以新分配的缓冲区)作为参数输入到cc>,但是记住要指定最大宽度(即scanf()),这样就不会溢出到未分配的内存中。
当您不再需要数据或在程序结束时,请记住在指向已分配内存的指针上使用SIZE-1——而在您的简单示例中,从技术上讲,这是不必要的,但很容易养成一个非常坏的习惯。

10-06 11:23