java char指针数组_将char指针数组传递给C中的函数?

首先,您应该包含必要的头文件 . 对于 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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值