简体   繁体   English

将字符数组传递给 function C++

[英]Pass char array on to a function C++

My goal is to take in a character array and replace specific words such as "class" with the word "video".我的目标是接收一个字符数组,并用“视频”这个词替换特定的词,例如“类”。 However, the data in buf array is coming from a web server that has unicode in it, so to my knowledge, I am not allowed to convert the char array into a string because it will mess up much of the data in it (I think).但是,buf 数组中的数据来自 web 服务器,其中包含 unicode,所以据我所知,我不允许将 char 数组转换为字符串,因为它会弄乱其中的大部分数据(我认为)。 So, my main question is, how do I pass buf in as an argument to the replaceWords function.所以,我的主要问题是,如何将 buf 作为参数传递给 replaceWords function。 Right now I get an error that says,现在我收到一条错误消息,

error: incompatible types in assignment of 'char*' to 'char [256]'错误:将“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;
}

The error is caused by buf = replaceWords(buf);该错误是由buf = replaceWords(buf);引起的. . This tries to assign the function return value ( char* ) to an array and that's not valid syntax.这试图将 function 返回值 ( char* ) 分配给数组,这不是有效的语法。

Your code passes the array to the function and the function changes the character string in-place.您的代码将数组传递给 function 和 function 就地更改字符串。 You don't need the return value from the function.您不需要 function 的返回值。 In fact, the function could just be defined as returning void and then you can remove the return statement.实际上,function 可以只定义为返回void ,然后您可以删除return语句。

Note: you should probably add some error checking.注意:您可能应该添加一些错误检查。 What happens if the badWord1 string is not found and strstr() returns NULL?如果没有找到badWord1字符串并且strstr()返回 NULL 会发生什么?

Look at this code:看看这段代码:

#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;
}

It will work as you intend.它将按您的意愿工作。 When you pass char buf[] you are passing a reference to the array you want to modify.当您传递char buf[]时,您正在传递对要修改的数组的引用。 That way you can modify it in the function and it will be modified everywhere else in the program.这样您就可以在 function 中对其进行修改,并且它将在程序中的其他任何地方进行修改。 There's not need to do additional assignment.不需要做额外的分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM