2D分配的数组(固定列数)作为函数的返回值

时间:2016-02-01 19:16:38

标签: c arrays pointers dynamic-memory-allocation

我想指点一些帮助: 在main函数中我初始化了应该指向数组的变量:

int main() {

int n;
double (*array)[3];
array = fillArray(&n);

该函数接收一个整数参数,该参数计算行数。函数的返回值应该是指向新创建的数组的指针,该数组将保存到main函数中的变量“array”中:

double (*)[3] fillArray(int * n) {
    double (*array)[3] = NULL;
    int allocated = 0;
    *n = 0;

    while (1)
    {
        /*scanning input*/

        if (allocated <= *n)
        {
        allocated += 10;
        array = (double(*)[3]) realloc (array, sizeof(*array) * allocated)
        }
        array[*n][0] = value1;
        array[*n][1] = value2;
        array[*n][2] = value3;
        (*n)++;
    }
    return array;
}

然而,返回值的类型不对,我有点丢失。谁能告诉我这段代码有什么问题?

提前谢谢你:)

2 个答案:

答案 0 :(得分:1)

您的代码具有不相关的语法错误和一些未声明的变量,但您询问的问题与函数fillArray()的声明形式有关。这个替代方案对我有用:

double (*fillArray(int * n))[3] {
    double (*array)[3] = NULL;

    /* ... */

    return array;
}

请注意表单与相同类型变量声明的相似性。

问题在于,尽管double (*)[3]是一个完全有效的类型指示符,例如,在演员表中使用它是不正确的,因为你试图声明对象的类型。

答案 1 :(得分:1)

given some guessing about items not mentioned in the question.

I think this is what you are looking for.

Notice the checking for success of the call to realloc()

Notice the #define of the magic numbers

#include <stdlib.h> // realloc(), exit(), EXIT_FAILURE

#define ALLOCATION_INCREMENT (10)
#define NUM_DOUBLES (3)

struct tagArray
{
    double arrayEntry[ NUM_DOUBLES ];
};

struct tagArray *fillArray(int *n);

int main( void )
{

    int n = 0;
    struct tagArray *array;

    if( NULL == (array = fillArray(&n) ) )
    { // then array generation failed
        exit( EXIT_FAILURE );
    }

    // implied else, array generation successful

    ....

    free( array );
    return 0;    
} // end function: main


struct tagArray *fillArray(int *n)
{
    struct tagArray *array = NULL;
    int allocated =0;

    while( 1 )
    {
        /* scanning input,
         * to acquire 'value1, value2, value3'
         * with some key input causes execution of 'break;'
         * */

        if( allocated <= *n )
        {
            allocated += ALLOCATION_INCREMENT;
            struct tagArray *temp = realloc (array, sizeof( struct tagArray) * allocated );

            if( !temp )
            { // then realloc failed
                free( array );
                return( NULL );
            }

            array = temp;
        }

        array[*n][0] = value1;
        array[*n][1] = value2;
        array[*n][2] = value3;
        (*n)++;
    }

    return array;
} // end function: fillArray