Search code examples
cpointersdynamic-memory-allocation

C : scanf skips the first iteration while taking char* inputs from user through scanf


I am trying to get Subject names from user using dynamic memory allocation and char **. I am not sure its the best way to do so.

Problem : scanf is getting skipped for first iteration in for loop. Tried with putting " %s", "\n%s" as suggested from StackOverflow but still facing the same.

Here is my code :

int nSubjects;
char **subNames;

printf("\nEnter no. of Subjects : ");
scanf("%d",&nSubjects);

subNames = malloc(nSubjects *  sizeof(char*));

 for(i=0;i<nSubjects;i++){

    *(subNames+i)= (char*)malloc(sizeof(char*));
    printf("\nEnter Subject %d name : ",i+1);
    fflush(stdin);
    scanf("%s",subNames[i]);
}

Complete code (if required): http://pastebin.com/7Ncw0mWF

Please guide me where I am doing wrong in this code. Any help will be highly appreciated.


Solution

  • You allocation is wrong for string in side loop:

    *(subNames+i)= (char*)malloc(sizeof(char*));
    

    should be:

    *(subNames+i)=  malloc(sizeof(char) * (string_lenght + 1));
    

    Additionally, don't use fflush(stdin); it causes undefined behavior on other then Microsoft compilers, Also don't cast returned address of malloc() and calloc() in C

    Read: Why fflush(stdin) is wrong?, and read: fflush @msdn.microsoft.