gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:37:24 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com