Search code examples
cloopsstructure

please can someone tell me why the program get stuck after entering the first element of the loop?


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxlong 20  

typedef struct {
    char name[maxlong];
    char surname[maxlong];
} personne;  

//writing the code to enter persons name and surname  
//.ffffffffffffffffffffffffffffffff

personne enterPersonne() {
    personne r;

    printf("write the surname: ");   
    scanf("%s",&r.name);
    printf("write the name : ");
    scanf("%s",&r.surname);

    return r;   
} 

int main (void)
{
    int dimension,i;
    personne *pers;

    printf("enter the persons count : "); 
    scanf("%d",&dimension);

    for(i=0; i<dimension; i++)
        *(pers+i) = enterPersonne(); 

    return 0;

}

Solution

  • Right before the for loop in main, you need to allocate a memory buffer to hold the contents of the pers array.

    A conventional way would to do this would be:

        pers = (personne *)malloc(dimension * sizeof(personne));
        if ( pers == NULL ) {
            // add code here to handle an out-of-memory condition
        }