Home > OS >  Sorting 2d array which store 10 city names
Sorting 2d array which store 10 city names

Time:12-13

Hi I am beginner in c and Want to sort 10 city names which is stored in 2d array
For example,
"goa" print first and "mumbai" print after "goa"
becuase in goa g come first compared to m in mumbai

#include<stdio.h>
#include<string.h>
int main(){

    char str[10][20]={"mumbai","goa","kanpur","bhopal","delhi","nagpur","jabalpur","thane","bhandup","kurla"};

    for(int i=0;i<10;i  )
    {
        for(int j=i 1;j<10;j  )
        {
            int p = strcmp(str[i],str[j]);
            if(p==-1 || p==0)
                continue;
            else
            {
                char tmp[1][20];
                tmp[0] = str[i];
                str[i] = str[j];
                str[j]= tmp[0];
            }
        }
    }
    for(int i=0;i<10;i  )
    {
        printf("%s\n",str[i]);
    }
    return 0;
}

above code not working but when I use below part of code in second for loop then its working

strcpy(tmp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], tmp);

can anyone explain me why this below logic is wrong in detail

tmp[0] = str[i];
str[i] = str[j];
str[j]= tmp[0];

CodePudding user response:

If I remember correctly, tmp[0] = str[i] would be assigning the address of the storage location for str[i] as the new address for the storage location of tmp[0]. Imaging putting your name on someone else's house.

strcpy is taking all the data in one row and copying it to the other row. Imagine asking a builder for a house just like your neighbor has.

CodePudding user response:

why this below logic is wrong in detail

Array are not pointers. Pointers are not arrays.

A string is a sequence of characters, up to and including the null character - usually stored in an array.

tmp[0] = str[i]; attempts to copy a pointer str[i] to an array.

Any form of a = b, does not copy a string or array, but perhaps a pointer. Copying pointers is insufficient for OP's swapping of strings.

To copy a string, use strcpy(c, d) to copy the string pointed to by d to the destination, pointed to by d.

  • Related