2

I can't access my pointer by index notation in main function. The way I'm passing the pointer as paramter to the functions, is that right ? I tried without the & and It didnt work neither. Here is my code:

//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;
}
PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90

1 Answers1

3

Rewrite function alloca_vetor the following way

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

And call function fill_vetor like

fill_vetor(array, num_linhas);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks. Now could you explain it to me? What is the `**`acc. Something like a pointer that points to another pointer? e.e – PlayHardGoPro Mar 14 '15 at 20:03
  • @PlayHardGoPro Array contas *array has to be passed to the function by reference. In this case any changes of array in the function will be reflected on the original array. Thus if you have declaration contas *array; then the pointer to this object will have type contas ** ; – Vlad from Moscow Mar 14 '15 at 20:08
  • Hey, I got `Segmentation Fault` error. But when I added `&` in the calling line, it appears that worked. Is it right ? – PlayHardGoPro Mar 14 '15 at 20:37
  • 1
    @PlayHardGoPro It is function fill_vector that has to be called with argument array without taking its address &. – Vlad from Moscow Mar 15 '15 at 05:03