Search code examples
cpointersdynamic-memory-allocationswapc-strings

I need to arrange names in alphabetical order using dynamic memory in c


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);
}

Solution

  • In this statement the size of the allocated memory is specified incorrectly

    name = (char**)malloc(n * sizeof(char));
                              ^^^^^^^^^^^^
    

    You have to write

    name = (char**)malloc(n * sizeof(char *));   
                              ^^^^^^^^^^^^^
    

    The swap function in general is incorrect. For starters it is unclear why there is used the magic number 20

    char temp[20];
    

    while the allocated character arrays have sizes equal to 100.

    name[i] = (char*)malloc(100 * sizeof(char));
    

    What you need is just to swap pointers pointing strings. For example the function swap can be declared and defined the following way

    void swap( char **a, char **b )
    {
        char *temp = *a;
        *a = *b;
        *b = temp;
    }
    

    and called like

    swap( name + i, name + j );
    

    Also to make the input safer you should write

    scanf( "%99s", *( name + i ) );
    

    Pay attention to that you should free all the allocated memory when the arrays will not required any more.