将char数组传递给函数C ++

时间:2020-04-16 01:46:10

标签: c++

我的目标是接受一个字符数组,并用“视频”一词替换诸如“类”之类的特定词。但是,buf数组中的数据来自其中包含unicode的Web服务器,因此,据我所知,我不允许将char数组转换为字符串,因为它会弄乱其中的许多数据(我认为)。 所以,我的主要问题是,如何将buf作为参数传递给replaceWords函数。现在,我收到一条错误消息

错误:将“ 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;
}

2 个答案:

答案 0 :(得分:1)

该错误是由buf = replaceWords(buf);引起的。这会尝试将函数返回值(char*)分配给数组,但这是无效的语法。

您的代码将数组传递给函数,并且函数就地更改了字符串。您不需要函数的返回值。实际上,可以仅将函数定义为返回void,然后删除return语句。

注意:您可能应该添加一些错误检查。如果找不到badWord1字符串并且strstr()返回NULL会怎样?

答案 1 :(得分:0)

看下面的代码:

#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[]时,将传递对要修改的数组的引用。这样,您可以在函数中对其进行修改,并且它将在程序中的其他任何地方进行修改。无需进行其他分配。

相关问题