c - 为什么我不能返回这个数组?

标签 c arrays return

为什么我会收到以下错误?

randmst.c: In function ‘main’:

randmst.c:41: error: variable-sized object may not be initialized

randmst.c: In function ‘createGraph’:

randmst.c:84: warning: return from incompatible pointer type

randmst.c:84: warning: function returns address of local variable

createGraph() 创建一个指向structs 的指针数组(称为VertexPointer)。创建后,我很难将其传递回 main()

int main(int argc, char **argv){

    //command line arguments
    int test = atoi(argv[1]);
    int numpoints = atoi(argv[2]);
    int numtrials = atoi(argv[3]);
    int dimension = atoi(argv[4]);

    //perform trials, put results in an array
    int i;
    int trials[dimension];
    for(i = 0; i < numtrials; i++){
        VertexPointer graph[numpoint= createGraph(numpoints, dimension);

        //testing
        int y;
        int i;
        for(y = 0; y < numpoints; y++){
            for(i = 0; i < dimension; i++){
                printf("%f \n", (*graph[y]).loc[i]);
            }
            printf("\n");
        }
    }


}



//an array of pointers holding the vertices of the graph
VertexPointer
createGraph(int numpoints, int dimension){
    //seed the psuedo-random number generator
    srand(time(NULL));

    //declare an array for the vertices
    VertexPointer graph[numpoints];

    //create the vertices in the array
    int x;
    int z;
    for(x = 0; x < numpoints; x++){
        //create the vertex
        VertexPointer v;
        v = (VertexPointer)malloc(sizeof(Vertex));
        (*v).key = 100;
        //(*v).prev = 0;
        //multiple dimensions
        for(z=0; z < dimension; z++){
            (*v).loc[z] = rand_float();
        }
        //put the pointer in the array
        graph[x] = v;
    }
    return graph;
}

最佳答案

C 不允许返回数组。即使确实如此,您的代码也会声明 createGraph 返回一个 VertexPointer,而不是它们的数组。 malloc 指针数组,更改代码以返回 VertexPointer *,并在 main 中使用指针而不是数组。

VertexPointer *
createGraph(int numpoints, int dimension) {
    ...
    VertexPointer *graph = malloc(numpoints * sizeof(*graph));
    ...
    return graph;
}

int main(int argc, char **argv) {
    ...
    VertexPointer *graph = createGraph(numpoints, dimension);
    ...
}

关于c - 为什么我不能返回这个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239008/

相关文章:

c - 使用 ICU 获取当前区域设置

c - 为什么编译器不从函数定义中推断出函数原型(prototype)?

c++ - 递归确定数组中的元素是否可以求和到目标 - C++

java - 在java数组中使用字符串

python - 将 np.where 应用于方括号过滤以进行 numpy 过滤

file - 在powershell中删除回车

c - 是否返回;在此功能中执行任何操作?

c++ - 如何在 Turbo C++ 16 位编译器中创建项目

C 程序语法(未编译)

mysql - 无法在 mysql 中存储执行语句的返回值