简体   繁体   中英

segmentation fault (Core dumped) error on Dynamic array

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

您的问题在于运算符的优先级: *items[i]计算结果为items[i][0]而您想要的是items[0][i] ,即:

(*items)[i]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM