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

时间:2014-03-07 00:19:42

标签: 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()创建一个指针数组(称为VertexPointer)到structs。一旦创建,我就无法将其传回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;
}

1 个答案:

答案 0 :(得分:1)

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