【问题标题】:Allocate memory dynamically of a vector of struct动态分配结构向量的内存
【发布时间】:2015-05-17 03:39:39
【问题描述】:

我无法通过主函数中的索引符号访问我的指针。我将指针作为参数传递给函数的方式,对吗?我试过没有&,但也没有用。这是我的代码:

//My Struct
typedef struct{
    int a;
    double d;
    char nome[20];
}contas;

//Function to allocate memory
void alloca_vetor(contas *acc, int linhas){
    acc = malloc(linhas * sizeof(contas));

    if(acc == NULL){
       printf("ERRO AO ALOCAR MEMORIA\n"); 
       exit(0);
    }

    printf("ALLOCATION SUCCESSFUL");
}

//Function to fill the vector
void fill_vetor(contas *acc, int linhas){
    int i,a;

    for(i=0; i< linhas; i++){
        acc[i].a = i;
    }
    printf("FILL SUCCESSFUL !\n");

    for(i=0; i< linhas; i++){
        printf("%i\n", acc[i].a);
    }
}

int main()
{
    int i,  num_linhas = 5;
    contas *array;

    alloca_vetor(&array, num_linhas);
    fill_vetor(&array, num_linhas);

// ERROR HAPPENS HERE - Segmentation Fault
    for(i=0; i < num_linhas; i++){
        printf("%i\n", array[0].a);
    }

    free(array);
    return 0;
}

【问题讨论】:

    标签: c vector struct dynamic-allocation


    【解决方案1】:

    按如下方式重写函数alloca_vetor

    void alloca_vetor( contas **acc, int linhas ){
        *acc = malloc(linhas * sizeof(contas));
    
        if(*acc == NULL){
           printf("ERRO AO ALOCAR MEMORIA\n"); 
           exit(0);
        }
    
        printf("ALLOCATION SUCCESSFUL");
    }
    

    并像调用函数fill_vetor一样

    fill_vetor(array, num_linhas);
    

    【讨论】:

    • 谢谢。现在你能给我解释一下吗? **acc 是什么。像指向另一个指针的指针之类的东西? e.e
    • @PlayHardGoPro Array contas *array 必须通过引用传递给函数。在这种情况下,函数中数组的任何更改都将反映在原始数组上。因此,如果您有声明 contas *array;那么指向该对象的指针将具有 contas ** 类型;
    • 嘿,我收到了Segmentation Fault 错误。但是当我在调用行中添加&amp; 时,它似乎有效。对吗?
    • @PlayHardGoPro 函数 fill_vector 必须使用参数数组调用而不获取其地址 &。