Reputation: 2933
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;
}
Upvotes: 2
Views: 845
Reputation: 310990
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);
Upvotes: 3