2013-05-10 172 views
1
#include <stdio.h> 
#include <string.h> 
void F1(void *comp, void *record){ 
    int complen = strlen((char *)comp), recordlen = *(int *)record; 
    *(int *)record = complen>recordlen ? complen : recordlen; 
} 

void F2(void *comp, void *ans){ 
    if(!*(char **)ans) 
     *(char **)ans = (char *)comp; 
    else if(strcmp((char *)comp, *(char **)ans) < 0) 
     *(char **)ans = (char *)comp; 
} 


void ProcessStrings(char ***vals, void* (*fp)(char *, void *), void *champ){ 
    char **copy = *vals; 
    while(*copy){ 
     fp(*copy++, champ); 
    } 
} 

int main() { 
    char *strings1[][100] = {{"beta", "alpha", "gamma", "delta", NULL}, {"Johnson", "Smith", "Smithson", "Zimmerman", "Jones", NULL}, {"Mary", "Bill", "Bob", "Zoe", "Annabelle", "Bobby", "Anna", NULL}}; 
    int maxLen = 0; 
    char *minString = NULL; 
    ProcessStrings(strings1, F1, &maxLen); 
    ProcessStrings(strings1, F2, &minString); 
    printf("Strings1: Max length is %d and min is %s\n", maxLen, minString); 
} 

快速背景...函數F1將字符串列表的最大長度提供給它的第二個參數。 F2按ASCII值提供最小字符串。指針指針

我的錯誤消息指出我傳遞了不兼容的指針類型來處理字符串。當我畫出指針時,我感覺好像我不是。幫幫我?

回答

0

確實傳遞了不兼容的指針類型。

strings1是指向字符的二維數組指針。請注意,C中的二維數組元素按行連續排列,而函數期望在ProcessStrings內的strings1首次解除引用後看到指針。

如果要在代碼正確地工作,就需要或者通過下面的結構來ProcessStrings

char **strings2[] = { 
     strings1[0], 
     strings1[1], 
     strings2[2] 
    }; 

或改變的功能的指針合作,以100個char指針的數組:

void ProcessStrings2(char * (*vals)[100], void (*fp)(void *, void *), void *champ){ 

順便說一句,你的函數似乎只處理字符串的第一行。