1. 解决方法
下面这样写会出错,因为作为函数的参数时,数组名会降级为指针,使用sizeof得到的结果将会始终为4(一个char指针的大小)。
char* dest_str;
char* src_str = "source char string";
strncpy(dest_str, src_str, sizeof(src_str));
正确应为:
dest_str= (char*)malloc(strlen(src_str) + 1); // 注意给'/0'留位置
strcpy(dest_str, src_str);
或者是
dest_str= strdup(src_str);
不过注意strdup不是c库标准函数,linux中不包括。所以如果需考虑移植性,使用第一种好点。
2. 参考资料
https://www.huwoo.net/2019/post-3168.html
https://stackoverflow.com/questions/13553113/char-array-split-ip-with-strtok