Home > Blockchain >  Function pointer in C?
Function pointer in C?

Time:09-17

I am beginner in C language and was learning about function pointer in C language. There I encountered a problem?

Write a compare function to sort by first character of name?

*int (firstnamecharcompar)(const void * a, const void * b))

Here is my code solution for this.

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

int compare1(const void *a,const void *b)
{
    char *c = *(char**)a;
    char *d = *(char**)b;
    return c[0] - d[0];                             
    //return ( *(char*)a[0] == *(char*)b[0] );                
}

int main()
{
    char* str[3];
    int i;
    for(i=0;i<3;i  )
    {
        str[i] = (char*)malloc(10*sizeof(char));
    }
    for(i=0;i<3;i  )
    {
        printf("Enter %d string => " , i 1 );
        scanf("%s", str[i]);                        
        printf("\n");
    }
    
    for(i=0;i<3;i  )
    {
        printf("%s ",str[i]);
    }
    
    qsort(str,3,10,compare1);
    
    for(i=0;i<3;i  )
    {
        printf("%s ",str[i]);
    }
    return 0;
}

But my code is getting terminated without giving any output? What is problem with my code?

CodePudding user response:

qsort(str,3,10,compare1); is wrong.

You are sorting an array of pointers. You need to pass in the size of the pointer, not the size of the object it is pointing to. That is, sizeof(char*) rather than 10.

CodePudding user response:

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

int compare1(const void *a, const void *b) {
    char *c = *(char **)a;
    char *d = *(char **)b;
    return c[0] - d[0];
    //return ( *(char*)a[0] == *(char*)b[0] );
}

int main() {
    char *str[3];
    int i;
    for (i=0; i<3; i  ) {
        str[i] = (char *)malloc(10*sizeof(char));
    }
    for (i=0; i<3; i  ) {
        printf("Enter %d string => ", i 1 );
        scanf("%s", str[i]);
        printf("\n");
    }

    for (i=0; i<3; i  ) {
        printf("%s ", str[i]);
    }

    qsort(str, 3, sizeof(char *), compare1); //HERE WAS AN ERROR!

    for (i=0; i<3; i  ) {
        printf("%s ", str[i]);
    }
    return 0;
}

Third parameter of qsort takes size of array element (in your case array contains char*, not char[10])

  • Related