The goal is to get 'n' number of names as input and arrange them in alphabetical order using dynamic memory allocation. If i input 4 names the code is working fine. But if i input more than 5, the code cuts off after i enter the fifth name. It is not accepting the 6th name even if i give n as 6. Can anyone tell me the reason why? And the solution to it? Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char[], char[]);
int main()
{
char** name;
int i, n, j, y;
printf("Enter the number of names:");
scanf("%d", &n);
name = (char**)malloc(n * sizeof(char));
for (i = 0; i < n; i++)
{
name[i] = (char*)malloc(100 * sizeof(char));
}
printf("Enter the names:\n");
for (i = 0; i < n; i++)
{
scanf("%s", *(name + i));
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
y = strcmp(name[i], name[j]);
if (y >= 0)
{
swap(name[i], name[j]);
}
}
}
for (i = 0; i < n; i++)
{
printf("%s\n", name[i]);
}
return 0;
}
void swap(char a[], char b[])
{
char temp[20];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
}