c版的回调函数与c++版的虚函数
C语言的回调函数思想代码:
#include <stdio.h>
void *max(void *base, unsigned int nmemb, unsigned int size,
int (*compar)(const void *, const void *))
{
int i;
void* max_data = base;
char* tmp = base;
for (i=1; i<nmemb; i++) {
tmp = tmp + size;
if (compar(max_data, tmp) < 0) {
max_data = tmp;
}
}
return max_data;
}
int compar_int(const void* x, const void* y)
{
return (*(int*)x - *(int*)y);
}
typedef struct _Student {
char name[16];
int score;
} Student;
int compar_student(const void* x, const void* y)
{
return (((Student*)x)->score - ((Student*)y)->score);
}
int main()
{
int data_int[] = {3, 2, 56, 41, 22, 7};
unsigned int count_int = sizeof(data_int) / sizeof(int);
int* max_int = (int*)max(data_int, count_int, sizeof(int), &compar_int);
printf("max int: %d\n", *max_int);
Student data_student[] = {
{"Kate", 92},
{"Green", 85},
{"Jet", 77},
{"Larry",88},
};
unsigned int count_student = sizeof(data_student) / sizeof(Student);
Student* high_score = (Student*)max(data_student,
count_student, sizeof(Student), &compar_student);
printf("high score -- name:%s, score:%d\n", high_score->name, high_score->score);
相关文档:
/***
*strtok.c - tokenize a string with given delimiters
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines strtok() - breaks string into series of token
* via repeated calls.
*
************************************************************** ......
哈哈!有幸在某网站发现这篇文章,读罢,觉得蛮有道理,发来大家一起共勉之
总是被同学们问到,如何学习C和C++才不茫然,才不是乱学,想了一下,这里给出一个总的回复。
一家之言,欢迎拍砖哈。
1、可以考虑先学习C.
大多数时候,我们学习语言的目的,不是为了成为一个语言专家,而是希望 ......
一、基本知识
指针和引用的声明方式:
声明指针: char* pc;
声明引用: char c = 'A'
char& rc = c;
它们的区别:
①从现象上看,指针在运行时可以改变其所指向的值,而引用一旦和某个对象绑定后 ......
刚开始学C/C++时,一直对字符串处理函数一知半解,这里列举C/C++字符串处理函数,希望对初学者有一定的帮助。
C:
char st[100];
1. 字符串长度
strlen(st);
2. 字符串比较
strcmp(st1,st2);
strncmp(st1,st2,n); 把st1,st2的前n个进行比较。
3. 附加
& ......
什么是空指针常量(null pointer constant)?
[6.3.2.3-3] An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
这里告诉我们:0、0L、'\0'、3 - 3、0 * 17 (它们都是“integer constant expression”)以及 (void*)0 等都是空 ......