开发者

Segfault using qsort

I need to sort an array of characters in order to iterate over it and print out the unique data points and their count. This array is held inside a linked list node, and I want to use qsort to do this. Unfortunately, I'm getting a segfault right at that particular line.

void printArray(Node_ptr node){

    int count=0; //character count

    char *temp= node->attribute开发者_如何转开发s; //duplicate attribute array



    char cur; //current char

    char *outputCat= emalloc(150); //concatenate counts to a single string

    outputCat= "Attribute %d counts are: ";



    qsort(&temp, lineCount, sizeof(char), compare); //sort the array

    ... more code
}

I cribbed the compare method from the man qsort page

int compare(const void *a, const void *b){

  return strcmp(*(char * const *) a, *(char * const *) b);

}

In DDD, the qsort line is the one that triggers the segfault. I originally thought it was due to inaccuracies in the parameters, so I put in some debugging printf statements. printf("%s", temp) prints out 1000 characters, which is exactly what linecount should be. Chars are 1 byte each, so no need for sizeof(char) here.

The error report from ddd on that line is

Program received signal SIGSEGV, Segmentation fault.    
0xb7f8c498 in ?? () from /lib/libc.so.6

Is this qsort's fault, or something else with my code?


This

qsort(&temp, lineCount, sizeof(char), compare);

Should be:

qsort(temp, lineCount, sizeof(char), compare);

You do not need to pass the address of a pointer!

qsort's first argument is a pointer, so if you pass it a pointer, you do not need to use the address-of operator, else you're passing a pointer to a pointer, which is not what you want in this case.


If you want to sort characters, the first argument to qsort() should be a character pointer, not a pointer to a character pointer. The same for the strcmp()

Also: please add the definition for struct node.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜