user968000 user968000 - 4 months ago 46
C Question

Difference between char** and char[][]

I am trying to sort strings using stdlib qsort. I have created two sort functions sort1 and sort2. sort1 input argument is char** and sort2 input argument is char[][]. My program crashes when use sort1 function to sort array of strings.

#include "stdafx.h"
#include <stdlib.h>
#include <string.h>


int compare(const void* a, const void* b)
{
const char *ia = (const char *)a;
const char *ib = (const char *)b;
return strcmp(ia, ib);
}

//program crashes
void sort1(char **A, int n1) {

int size1 = sizeof(A[0]);
int s2 = n1;
qsort(A,s2,size1,compare);
}

//works perfectly
void sort2(char A[][10], int n1) {

int size1 = sizeof(A[0]);
int s2 = n1;
qsort(A,s2,10,compare);

}

int _tmain(int argc, _TCHAR* argv[])
{

char *names_ptr[5] = {"norma","daniel","carla","bob","adelle"};
char names[5][10] = {"norma","daniel","carla","bob","adelle"};
int size1 = sizeof(names[0]);
int s2 = (sizeof(names)/size1);
sort1(names_ptr,5); //doesnt work
sort2(names,5); //works
return 0;
}

M.M M.M
Answer

The qsort function receives a pointer to the thing being sorted. In sort2 you are sorting arrays of 10 char. In sort1 you are sorting pointers to char.

So the compare function is wrong for sort1, because the arguments are pointers to pointers to char (converted to void *), but you cast to pointer to char.

The sort2 works because converting a pointer to array of 10 char into a pointer to char (via void *) produces a pointer that points to the first character of those 10.

You need to use a different compare function for each of these two cases, because you are sorting different things.

Comments