[英]How to use array of pointers in structure if i don't know array size
Suppose we have an array of pointers called int *weights[]
in structure Graph
and we initialize it 假设我们在结构
Graph
有一个称为int *weights[]
的指针数组,并对其进行了初始化
int CreateGraph(Graph *G, int vexs){
G->n = vexs;
for(int i = 0; i < G->n; i++){
G->weights[i] = (int*)malloc(sizeof(int)*G->n);
}
for(int i = 0; i < G->n; i++){
for (int j = 0; j<G->n; j++) {
G->weights[i][j] = j;
}
}
return 1;//just for test
}
also we have a function to show the graph 我们还有一个显示图表的功能
void show(Graph G){
for(int i = 0; i<G.n; i++){
for (int j = 0; j<G.n; j++) {
printf("%d",G.weights[i][j]);
}
}
}
in main 在主要
Graph *g = (Graph *)malloc(sizeof(Graph));
CreateGraph(g, 3);
show(*g);
it crashed and xcode said EXC_BAD_ACCESS (code=1, address=0x0),but i have another worked version of function show 它崩溃了,xcode表示EXC_BAD_ACCESS(代码= 1,地址= 0x0),但是我还有另一个函数show的工作版本
void success_show(Graph *G)
typedef struct {
int n;
int *weights[];
}Graph;
show(Graph G) success_show(Graph *G)
. show(Graph G) success_show(Graph *G)
。 G->weights[i] = (int*)malloc(sizeof(int)*G->n);
G->weights[i] = (int*)malloc(sizeof(int)*G->n);
初始化指针数组G->weights[i] = (int*)malloc(sizeof(int)*G->n);
You have to allocate memory for G->weights
. 您必须为
G->weights
分配内存。
G->weights = (int**) malloc(sizeof(int*)*G->n);
And then allocate memory for each individual pointer element. 然后为每个单独的指针元素分配内存。
for(i=0; i<G->n; i++)
{
G->weights[i] = (int*) malloc(sizeof(int)*<entersize>);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.