Question

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.

Was it helpful?

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.

OTHER TIPS

Your malloc is wrong:

 *(subNames[i]) = (char*)malloc(sizeof(char*));

You are trying to allocate memory for a char** which is actually then being converted to a char*. You also need the specify the size of length, or this will allocate a single pointer. Note: subNames[i] doesn't need to be dereferenced.

The below should work:

  (subNames[i]) =  (char*)malloc(sizeof(char) * (string_length + 1));

Note: you will have to declare the string length variable, maybe perhaps as 1000, and then realloc it to the strlen of the string entered afterwards.

If your compiler is gcc and your gcc> 2.7, you can use "%ms". this will allow scanf to allocate memory for your pointer:

for(i=0;i<nSubjects;i++){
    printf("\nEnter Subject %d name : ",i+1);
    scanf("%ms",&subNames[i]);
}

How to store a character string into a character pointer declared in a structure

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top