0

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.

Kartik Domadiya
  • 29,868
  • 19
  • 93
  • 104

3 Answers3

2

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.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
0

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.

Joseph
  • 589
  • 1
  • 5
  • 13
0

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

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    Whether the completely non-portable %ms hack works is not a feature of the compiler, but of the standard IO library, of which scanf is a part of. So it's likely a glibc thing, not a gcc thing. – Jens Jan 30 '14 at 07:45