以下是Richard Reese的“了解和使用C指针”的示例。 我的问题是它应该是“typedef int(* fptrOperation)......”在第7行吗? 我尝试了他们两个,但他们都运作良好。我搜索了使用typedef和指针在线两天的功能,但仍然没有弄明白。 感谢您的任何帮助~~typedef和指向C中的函数
#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;
}
https://stackoverflow.com/questions/17914057/is-an-asterisk-optional-in-a-function-指针 –
带有-Wall选项的gcc没有警告,我想对于如何声明函数指针没有限制。编译器自己做这个魔术,因为当编译sort(names,5,compareIgnoreCase);'时,没有其他方式使用'compareIgnoreCase'的地址。 – LPs