Search code examples
cstringpointersmallocgets

dynamic memory allocation for strings


int ReadNames(char ***Names, int *n)    
{    
int i, k;    
char name[100];    
printf("Enter how many names\n");    
scanf("%d", n);       
/* Allocate memory and read names */
*Names=(char **)malloc((*n)*sizeof(char *));
for(i=0;i<(*n);i++)
{
    *(*Names+i)=(char*)malloc(sizeof(name));
    gets(name);
    strcpy(*(*Names+i),name);
}

for(i=0;i<(*n);i++)
    printf("%s\n",*(*Names+i));
return 1;
}    
void main()        
{
char **Names;
int n, i;
ReadNames(&Names, &n);
}

This program is running fine...but there is slight difference from what i am expecting. Problem is when i am entering value of 'n' as 3, it is able to read only 2 strings and prints those two strings....ie. it reads n-1 strings and prints n-1 strings. Anything wrong in my code.


Solution

  • just add getchar() after scanf()

    so that each '\n' gets disposed of while taking input. Your code will be

    int ReadNames(char ***Names, int *n)
    {
        int i, k;
        char name[100];
        printf("Enter how many names\n");
        scanf("%d", n);
        getchar(); // eats unnecessary '\n' in the buffer
        /* Allocate memory and read names */
        *Names=(char **)malloc((*n)*sizeof(char *));
        for(i=0;i<(*n);i++)
        {
                *(*Names+i)=(char*)malloc(sizeof(name));
                    gets(name);
                        strcpy(*(*Names+i),name);
        }
    
        for(i=0;i<(*n);i++)
                printf("%s\n",*(*Names+i));
        return 1;
    }
    void main()
    {
        char **Names;
        int n, i;
        ReadNames(&Names, &n);
    }