将函数返回的数组分配给一行2d数组C编程

时间:2017-02-06 11:32:55

标签: c arrays function

我有一个返回缓冲区数组的函数。调用函数有一个2d数组,我需要将返回的数组只分配给2d数组的特定行。我的代码不起作用。请帮我理解我的错误。

在通话功能中:

char buff[5][BUFF_SIZE] = {{0}};
char statement[] = "USE THIS STATEMENT;";
char name[] = "some_name";
int value1 = 90;
double value2 = 20;

/**The statement below causes the error that array is not assignable **/
buff[0] = function(statement, name, value1, value2));   
if( buff[0] != NULL)
   // do stuff

功能:

char *function(char *statement, char *name, int value1, double value2)
{
    size_t size = BUFF_SIZE;

    char *buff = malloc (size);
    int nchars;
    if (buff == NULL)
        return NULL;

    /* Try to print in the allocated space. */
    nchars = snprintf(
                      buff,
                      BUFF_SIZE,
                      statement,
                      value1,
                      value2,
                      name
                      );
    if (nchars >= size)
    {
        /* Reallocate buffer now that we know
         how much space is needed. */
        size = nchars + 1;
        buff = realloc (buff, size);

        if (buff != NULL)
              /* Try again. */
              snprintf(
                      buff,
                      size,
                      statement,
                      value1,
                      value2,
                      name
                    );
    }
    /* The last call worked, return the string. */
    return buff;
}

非常感谢! 编辑:纠正了第二次调用snprintf中的错误

1 个答案:

答案 0 :(得分:1)

您有以下声明:

char buff[5][BUFF_SIZE] = {{0}};

chars的2D数组。但是,您的函数会返回char *,这与buff的行不兼容,因为它们没有char *类型。所以用以下内容替换你的声明:

char *buff[5] = {NULL};

这是指向char的指针(在本例中为5)的数组。然后为它分配内存:

for (i = 0; i < 5; i++)
{
    buff[i] = malloc (size*sizeof(char));    //or just malloc(size);
    if (buff[i] == NULL)
        printf ("Error allocating memory\n");
}