Source code for implementing callback functions in C Language

Source: Internet
Author: User

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

Typedef char byte;

Typedef int (_ stdcall * comparefunction) (const byte *, const byte *);

Void _ stdcall bubblesort (byte * array, int size, int elem_size, comparefunction cmpfunc)
{
For (INT I = 0; I <size; I ++)
{
For (Int J = 0; j <size-1; j ++)
{
// Callback comparison Function
If (1 = (* cmpfunc) (array + J * elem_size, array + (J + 1) * elem_size ))
{
// Two elements are exchanged.
Byte * temp = new byte [elem_size];
Memcpy (temp, array + J * elem_size, elem_size );
Memcpy (array + J * elem_size, array + (J + 1) * elem_size, elem_size );
Memcpy (array + (J + 1) * elem_size, temp, elem_size );
Delete [] temp;
}
}
}
}

//////////////////////////////////////// //////////////////////////////////
// For the user, a callback function must be provided, and its address must be passed to the bubblesort () function. There are two simple examples below,
// One compares two integers and the other compares two strings:

Int _ stdcall compareints (const byte * velem1, const byte * velem2)
{
Int elem1 = * (int *) velem1;
Int elem2 = * (int *) velem2;
If (elem1 <elem2)
Return-1;
If (elem1> elem2)
Return 1;
Return 0;
}

Int _ stdcall comparestrings (const byte * velem1, const byte * velem2)
{
Const char * elem1 = (char *) velem1;
Const char * elem2 = (char *) velem2;
Return strcmp (elem1, elem2 );
}
//////////////////////////////////////// //////////////////////////////////

Int main (INT argc, char * argv [])
{
Int I;
Int array [] = {5432,432 1, 3210,210 9, 1098 };
Printf ("Before sorting ints with bubblesort: \ n ");
For (I = 0; I <5; I ++)
Printf ("% d", array [I]);
Bubblesort (byte *) array, 5, sizeof (array [0]), & compareints );
Printf ("\ nafter the sorting: \ n ");
For (I = 0; I <5; I ++)
Printf ("% d", array [I]);
Printf ("\ n ");

System ("pause ");
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.