1
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <string.h>
void swaps(char*s,char*t)
{
    char*a = t;
    strcpy(t,s);
    strcpy(s,a);
}
int main(void)
{
    int n=GetInt();
    char* a[n];
    int c=0;
    for(int i=0;i<n;i++)
    {
        a[i]=GetString();
    }
    puts("");
    for(int j=0;j<n;j++)                                  
    {
        for(int i=0;i<n-1;i++)
        {
            c=strcmp(a[i],a[i+1]);
            if(c>0)
            {
                swaps(a[i],a[i+1]);
            }
        }
    }
    for(int i=0;i<n;i++)
    {
         printf("%s\n",a[i]);   
    }
    return 0;
}

I am trying to arrange strings in alphabetic order using pointers.I was able to get desired output using 2d char arrays but not able to get the correct output using pointers.

1 Answer 1

1

Here I see a problem with the swaps function and the indexes of a [i], as I believe on the return of the swaps function is lost control of the indexes i. Your swaps function ends with the assignment of s and t to the same string, We could do something like

void swaps(char*s,char*t)
{
    char* temp = s;
    s = t;
    t = temp;
}

Which actually exchanges the values of the s and t pointers, but it does not work either because we are not able to change the memory addresses that point a[i] and a[i + 1], ie the output would be the same as the input

a simple way is to avoid this function and do a swap directly on main. I wrote this version of your program that I think works well:

#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    int n = GetInt();
    char* a[n];
    int c = 0;
    for(int i = 0; i < n; i++)
    {
        a[i] = GetString();
    }
    puts("");
    for(int j = 0; j < n; j++)                                  
    {
        for(int i = 0; i < n; i++)
        {
            if(j != i)
            {
                c = strcmp(a[i],a[j]);
                if(c > 0)
                {
                    char* temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }        
        }
    }
    for(int i = 0; i < n; i++)
    {
         printf("%s\n", a[i]);
    }
    return 0;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .