I am trying to pass a structure's array to a function, but it gives me an error when i becomes 1, acces violation.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
typedef struct {
int locuri;
int putere;
char marca[50];
char culoare[50];
int an_fabricatie;
}automob;
void aloca(automob **autos, int n)
{
*autos = (automob*)malloc(sizeof(automob)*n);
if (autos == NULL) {
exit(1);
}
}
void read_autos(const char* filename, automob **A, int *n)
{
FILE *f_in = fopen(filename, "r");
int i = 0, aux;
if (f_in == NULL) {
printf("Nu s-a gasit fisierul!");
_getch();
exit(0);
}
fscanf(f_in, "%d", n);
aloca(A, *n);
while (i < (*n)) {
fscanf(f_in, "%d", &A[i]->locuri);
fscanf(f_in, "%d", &A[i]->putere);
fscanf(f_in, "%s", &A[i]->marca);
fscanf(f_in, "%s", &A[i]->culoare);
fscanf(f_in, "%d", &A[i]->an_fabricatie);
i++;
}
}
void main()
{
int n;
automob *A;
read_autos("autos.in", &A, &n);
_getch();
}
I think the pointer A is not allocated properly but I really don't know. Do you have any ideas? Because this works when I write it in the main function but does not work if I right it in another function like read_autos.
&in your fscanf statements. Example :&A[i]->locurishould be&(A[i]->locuri)void main()please.