sorting an array of strings using qsort

C

Cstudent

Im getting and "EXC_BAD_ACCESS" runtime error with my code. Can anyone
help me out?

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



static int sortstring( const void *str1, const void *str2 );
typedef int (*funcptr)();

int main (int argc, const char * argv[])
{
int inx = 0;
funcptr p_sortstring;
char *starr[] =
{
"dog",
"Arm",
"Cat",
"Eric",
"Bat",
"Fork",
"hello",
"Geroge",
"Mike",
"Alabama"
};

size_t count = sizeof(starr)/sizeof(*starr);
qsort( starr, count, sizeof(char*), p_sortstring );
for (inx = 0; inx < 10; inx++)
printf("%s ", starr[inx]);




return 0;
}

static int sortstring( const void *str1, const void *str2 )
{
const char *rec1 = str1;
const char *rec2 = str2;
int val = strcmp(rec1, rec2);


return val;
}
 
L

luserXtrog

Im getting and "EXC_BAD_ACCESS" runtime error with my code. Can anyone
help me out?

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

static int sortstring( const void *str1, const void *str2 );
typedef int (*funcptr)();

int main (int argc, const char * argv[])
{
        int inx = 0;
        funcptr p_sortstring;

A pointer gots to point to something!
try:
funcptr p_sortstring = sortstring;
Or eliminate the variable entirely and just use sortstring
directly as argument.
        char *starr[] =
        {
                "dog",
                "Arm",
                "Cat",
                "Eric",
                "Bat",
                "Fork",
                "hello",
                "Geroge",
                "Mike",
                "Alabama"
        };

        size_t count = sizeof(starr)/sizeof(*starr);
        qsort( starr, count, sizeof(char*), p_sortstring );

p_sortstring wasn't initialized, so qsort receives a
pointer of indeterminate value.
        for (inx = 0; inx < 10; inx++)
                printf("%s ", starr[inx]);

        return 0;

}

static int sortstring( const void *str1, const void *str2 )
{
        const char *rec1 = str1;
        const char *rec2 = str2;
        int val = strcmp(rec1, rec2);

        return val;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top