[英]Pass char array on to a function C++
我的目标是接收一个字符数组,并用“视频”这个词替换特定的词,例如“类”。 但是,buf 数组中的数据来自 web 服务器,其中包含 unicode,所以据我所知,我不允许将 char 数组转换为字符串,因为它会弄乱其中的大部分数据(我认为)。 所以,我的主要问题是,如何将 buf 作为参数传递给 replaceWords function。 现在我收到一条错误消息,
错误:将“char*”分配给“char [256]”时的类型不兼容
char buf[256];
buf = replaceWords(buf);
char * replaceWords(char* buf) {
char badWord1[] = "class";
char * occurrence = strstr(buf, badWord1);
strncpy(occurrence, "video", 5);
return buf;
}
该错误是由buf = replaceWords(buf);
引起的 . 这试图将 function 返回值 ( char*
) 分配给数组,这不是有效的语法。
您的代码将数组传递给 function 和 function 就地更改字符串。 您不需要 function 的返回值。 实际上,function 可以只定义为返回void
,然后您可以删除return
语句。
注意:您可能应该添加一些错误检查。 如果没有找到badWord1
字符串并且strstr()
返回 NULL 会发生什么?
看看这段代码:
#include <bits/stdc++.h>
using namespace std;
void replaceWords(char buf[]) {
char badWord1[] = "class";
char * occurrence = strstr(buf, badWord1);
strncpy(occurrence, "video", 5);
}
int main() {
char temp[5];
temp[0] = 'c';
temp[1] = 'l';
temp[2] = 'a';
temp[3] = 's';
temp[4] = 's';
replaceWords(temp);
cout << temp << endl;
return 0;
}
它将按您的意愿工作。 当您传递char buf[]
时,您正在传递对要修改的数组的引用。 这样您就可以在 function 中对其进行修改,并且它将在程序中的其他任何地方进行修改。 不需要做额外的分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.