简体   繁体   中英

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). So, my main question is, how do I pass buf in as an argument to the replaceWords function. Right now I get an error that says,

error: incompatible types in assignment of 'char*' to '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);. This tries to assign the function return value ( char* ) to an array and that's not valid syntax.

Your code passes the array to the function and the function changes the character string in-place. You don't need the return value from the function. In fact, the function could just be defined as returning void and then you can remove the return statement.

Note: you should probably add some error checking. What happens if the badWord1 string is not found and strstr() returns 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. That way you can modify it in the function and it will be modified everywhere else in the program. There's not need to do additional assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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