Reputation: 13
I am having this issue when trying to build my dynamic array, I think that there is mystake on realloc function or something, would appreciate if you can give me a hand on it. I am able to enter the names the first time but the issue start when Im doing it the second time
typedef struct {
char nom[30], prenom[20];
int age;
} ITEM;
void Lire(ITEM **items, int *nb_items)
{
int i = 0;
printf("* Entrer les donnees et taper . pour terminer\n\n");
for (i = 0; TRUE; i++)
{
ITEM *temp = (ITEM *) realloc(*items, ((i + 1) * sizeof(ITEM)));
if (temp == NULL)
{
free(*items);
printf("Il n'y a pas de memoire! \n");
exit (0);
}
*items = temp;
printf("> nom : ");
scanf("%s", (*items[i]).nom);
if ((*items[i]).nom[0] == '.')
break;
printf("> prenom : ");
scanf("%s", (*items[i]).prenom);
}
}
int main(int argc, char *argv[])
{
ITEM *items;
int nb_items=0;
items = (ITEM *) malloc(sizeof(ITEM));
if(items == 0)
{
printf("Il n'y a pas de memoire! \n");
exit (0);
}
Lire(&items, &nb_items);
free (items);
exit(0);
}
Upvotes: 0
Views: 534
Reputation: 50180
to make life easier i would do
*items = temp;
ITEM *current = &temp[i];
printf("> nom : ");
scanf("%s", current->nom);
...etc
makes the code easier to read and simplifies the whole operator precedence isuuse
Upvotes: 0
Reputation: 229593
Array subscript access binds tighter than *
. This causes *items[i]
to be interpreted as *(items[i])
, for example in this statement:
scanf("%s", (*items[i]).nom);
So items
is accessed as if it would be an array of pointers to ITEM
. In reality it is a pointer to an array of ITEM
structs, and should be accessed like this:
scanf("%s", (*items)[i].nom);
Upvotes: 1
Reputation: 5163
You problem is in operator precedence: *items[i]
evaluates to items[i][0]
and you want items[0][i]
, which is:
(*items)[i]
Upvotes: 2