二维分配数组(固定列数)作为函数的 return 值

2D allocated array (fixed number of columns) as return value of a function

我想得到一些帮助: 在主函数中,我已经初始化了应该指向数组的变量:

int main() {

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

该函数接收一个整数参数,用于计算行数。函数的return值应该是一个指向新建数组的指针,会保存到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;
}

但是,return 值的类型不正确,我有点迷路了。谁能告诉我这段代码有什么问题吗?

提前谢谢你:)

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

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

    /* ... */

    return array;
}

注意在形式上与相同类型的变量声明的相似性。

问题在于,尽管 double (*)[3] 是一个完全有效的类型指示符,例如,在强制转换中,但完全按照您尝试 declare[ 的方式使用它是不正确的=20=]对象的类型。

对问题中未提及的项目进行了一些猜测。

我想这就是您要找的。

注意检查对 realloc()

的调用是否成功

注意 magic 数字的 #define

#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