简体   繁体   English

如果我不知道数组大小,如何在结构中使用指针数组

[英]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)

Graph 图形

typedef struct {
    int n;
    int *weights[];
}Graph;

Question: 题:

  • What's the difference between using Graph *G and Graph G as function parameter here show(Graph G) success_show(Graph *G) . 在这里使用Graph * G和Graph G作为函数参数有什么区别show(Graph G) success_show(Graph *G)
  • is it ok to initialize array of pointer using 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM