首先,您应该包含必要的头文件 . 对于 strcmp ,您需要 ,对于 malloc . 你还需要在main之前至少声明测试 . 如果这样做,您会注意到以下错误:
temp.c: In function ‘test’:
temp.c:20:5: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [enabled by default]
/usr/include/string.h:143:12: note: expected ‘const char *’ but argument is of type ‘char’
这表明 test() 应该有 char * 作为第一个参数 . 总而言之,您的代码应如下所示:
#include /* for strcmp */
#include /* for malloc */
int test(char*,char**); /* added declaration */
int main(){
char **array;
char a[5];
int n = 5;
array = malloc(sizeof(*array));
array[0] = malloc(n * sizeof(**array));
/*Some code to assign array values*/
test(a, array);
free(*array); /* free the not longer needed memory */
free(array);
return 0;
}
int test(char * s1, char **s2){ /* changed to char* */
if(strcmp(s1, s2[0]) != 0) /* have a look at the comment after the code */
return 1;
return 0;
}
编辑
请注意strcmp使用以null结尾的字节字符串 . 如果 s1 和 s2 都不包含空字节,则 test 中的调用将导致分段错误:
[1] 14940 segmentation fault (core dumped) ./a.out
要么确保两者都包含空字节 '\0' ,要么使用strncmp并更改 test 的签名:
int test(char * s1, char **s2, unsigned count){
if(strncmp(s1, s2[0], count) != 0)
return 1;
return 0;
}
/* don' forget to change the declaration to
int test(char*,char**,unsigned)
and call it with test(a,array,min(sizeof(a),n))
*/
你的内存分配也是错误的 . array 是 char** . 您为 *array 分配内存,它本身就是 char* . 你永远不会为这个特定的指针分配内存,你错过了 array[0] = malloc(n*sizeof(**array)) :
array = malloc(sizeof(*array));
*array = malloc(n * sizeof(**array));