Iv'e looked around but couldn't find a case similar to mine.
I am trying to swap 2 string pointers to sort a char***
so I am trying to start by "sorting" only one string to see if I am right.
#include <stdio.h>
void printAllStrings(const char *** all)
{
int i;
int j;
int k;
for (i = 0; all[i] != NULL; i++)
{
for (j = 0; all[i][j] != NULL; j++)
{
for (k = 0; all[i][j][k] != NULL; k++)
{
printf("%c", all[i][j][k]);
}
printf(" ");
}
printf("\n");
}
}
void swap(char **a, char **b)
{
char *c = *a;
*a = *b;
*b = c;
}
void sort(const char *** all)
{
int i;
int j;
char * minString = all[0][0];
for (i = 0; all[i] != NULL; i++)
{
for (j = 0; all[i][j] != NULL; j++)
{
if (strcmp(minString, all[i][j])>0)
{
minString = all[i][j];
}
}
}
swap(&all[0][0], &minString);
}
void main()
{
char * arrP1[] = { "father", "mother", NULL };
char * arrP2[] = { "sister", "brother", "grandfather", NULL };
char * arrP3[] = { "grandmother", NULL };
char * arrP4[] = { "uncle","aunt", NULL };
char ** arrPP[] = { arrP1, arrP2, arrP3, arrP4 , NULL };
printAllStrings(arrPP);
sort(arrPP);
printAllStrings(arrPP);
}
The first "printAllStrings" prints normally, unsorted:
father mother
sister brother grandfather
grandmother
uncle aunt
The second "printAllStrings" prints:
aunt mother
sister brother grandfather
grandmother
uncle aunt
So it moved the first pointer over to "aunt" but the second pointer still pointed on "aunt" as well. The weird part is that I debugged and actually saw them swapping like you would expect, but when I print I see that they didn't. I can't get whats wrong here.
I was expecting the 2 strings (father,aunt) to swap (not actually swap in the memory just swap pointers) and then to be printed like so:
aunt mother
sister brother grandfather
grandmother
uncle father
Iv'e tried both answers and they both gave me something like this:
-gibrish- mother
sister brother grandfather
grandmother
uncle aunt
And no guys, I haven't gotten any warning / errors from the compiler. I still don't get it.
When I try to swap within the "sort" function by saving the "minString" indexes it works just fine, I'm just not sure if the 2 strings actually change addresses or just the pointers:
char * tmp = all[0][0];
all[0][0] = minString;
all[indexI][indexJ] = tmp;
Output:
aunt mother
sister brother grandfather
grandmother
uncle father
Also a part of the question is to ONLY swap pointers, and not the actual strings.