0

int my_compare( const void* a, const void* b )
{
    char* str1 = (char*)a;
    char* str2 = (char*)b;

    return strcmp( str1, str2 );
}

int main()
{
  char d[5][10];

  strcpy( d[0], "123456789");
  strcpy( d[1], "1");
  strcpy( d[2], "7");
  strcpy( d[3], "200000");
  strcpy( d[4], "300400000");

  qsort( d, 5, sizeof(char*), my_compare );
}

This doesn't seem to be OK.

How do I sort the array of strings in this case?

5
  • 2
    The size of each element is sizeof d[0] (which is 10), not sizeof(char*) Commented Mar 27, 2024 at 16:50
  • 2
    Each element in d is not a char* but a char[10]. This means that the size-parameter you pass to qsort() should be 10 or better *d Commented Mar 27, 2024 at 16:51
  • What specifically does "This doesn't seem to be OK." mean? What were you expecting? Commented Mar 27, 2024 at 16:52
  • 2
    Your code would be correct if it were char *d[5]; and you then did d[0] = "123456789"; ... Commented Mar 27, 2024 at 16:54
  • Changing the qsort line to qsort( d, 5, 10, my_compare ); fixes it. Thanks. Commented Mar 28, 2024 at 10:47

1 Answer 1

3

The problem in your code is that sizeof(char*) is the size of a pointer (usually 4 or 8 depending on your platform), but you need to provide the size of one element which is 10.

In the following code the all sizes (maximum string length and number of strings) are calculated with the the sizeof operator.

Explanation:

  • int maxstrlength = sizeof(d[0]); : this is the size of one string element (10 in your case)
  • int nbofstrings = sizeof(d) / sizeof(d[0]); : this is the number of elements (or strings). IOW the total size of d (50 here) divided by the size of one element (10) which is 5.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int my_compare(const void* a, const void* b)
{
  const char* str1 = (const char*)a;
  const char* str2 = (const char*)b;

  return strcmp(str1, str2);
}

int main()
{
  char d[5][10];

  strcpy(d[0], "123456789");
  strcpy(d[1], "1");
  strcpy(d[2], "7");
  strcpy(d[3], "200000");
  strcpy(d[4], "300400000");

  int maxstrlength = sizeof(d[0]);
  int nbofstrings = sizeof(d) / sizeof(d[0]);

  for (int i = 0; i < nbofstrings; i++)   // display strings before sorting
    printf("d[%d] = \"%s\"\n", i, d[i]);

  printf("\n");

  qsort(d, nbofstrings, maxstrlength, my_compare);

  for (int i = 0; i < nbofstrings; i++)   // display strings after sorting
    printf("d[%d] = \"%s\"\n", i, d[i]);
}

BTW: in my_compare the pointers should be casted to const char* rather than char*, but this is nitpicking.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.