这是Richard Reese的“理解和使用C指针”中的一个示例。我的问题是第七行应该是“ typedef int(* fptrOperation)......”吗?我尝试了两个,但是它们都工作良好。我搜索了typedef和在线函数指针的用法两天,但仍然没有弄清楚。谢谢你的帮助~~
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef int (fptrOperation)(const char*, const char*);//
char* stringToLower(const char* string) {
char *tmp = (char*) malloc(strlen(string) + 1);
char *start = tmp;
while (*string != 0) {
*tmp++ = tolower(*string++);
}
*tmp = 0;
return start;
}
int compare(const char* s1, const char* s2) {
return strcmp(s1,s2);
}
int compareIgnoreCase(const char* s1, const char* s2) {
char* t1 = stringToLower(s1);
char* t2 = stringToLower(s2);
int result = strcmp(t1, t2);
free(t1);
free(t2);
return result;
}
void displayNames(char* names[], int size) {
for(int i=0; i<size; i++) {
printf("%s ",names[i]);
}
printf("\n");
}
void sort(char *array[], int size, fptrOperation operation) {
int swap = 1;
while(swap) {
swap = 0;
for(int i=0; i<size-1; i++) {
if(operation(array[i],array[i+1]) > 0){
swap = 1;
char *tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
}
}
}
}
int main(int argc, char const *argv[])
{
char* names[] = {"Bob", "Ted", "Carol", "Alice", "alice"};
sort(names,5,compareIgnoreCase);
displayNames(names,5);
return 0;
}
不要紧。
这是因为对于函数参数,函数类型会自动转换为函数指针(ISO / IEC 9899: 2011、6.7.6.3,§8):
如6.3.2.1中所述,将参数声明为“函数返回类型”声明调整为“指向函数返回类型的指针”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句