c++指针做参数,如何修改参数指向的内容

我是想把字符串内容修改为‘xx’,但是在只能修改形参的内容无法修改实参的内容,请问replaceSpace这个函数该如何修改才能在main函数调用后把它的字符串修改为‘xx’,谢谢。

 class Solution {
public:
    void replaceSpace(char *str,int length) {
        char s[2] = {0};
        s[0] = 'x';
        s[1] = 'x';
        s[2] = '\0';
        str = s;
        std::cout << str << std::endl;
    }
};

int main()
{
    Solution sol;
    char *s = "ss";
    sol.replaceSpace(s, 2);
    std::cout << s << std::endl;
    return 0;
}
 char *s = "ss";
这是常量不能修改,修改为
char s[100] = "ss";

我用手机的,没法把我代码粘给你,但我博客有,就是剑指offer上有一题,将字符串中空格替换为%20的,你借鉴下,可以去我博客剑指offer部分代码那一篇

话说没越界吗?char s[2] 只有两个元素吧

replace函数有问题,你使用了数组大小为3的,而不是2,要修改的话,移动指针就行了,你这样写不好,那个结束符号是已经存在的

个人认为,既然用了C++,为什么不再多用一点C++的东西呢,加个string,加个引用,轻轻松松啊。
class Solution {
public:
void replaceSpace(std::string& s) {
s="xx";
std::cout << s.c_str() << std::endl;

}

};

int main()
{
Solution sol;
std::string s = "ss";
sol.replaceSpace(s);
std::cout << s.c_str() << std::endl;
system("pause");
return 0;
}

首先你的代码运行出错,应该改为s[3]
楼主可以试试这样

#include<iostream>
#include<cstring>
     class Solution {

public:
void replaceSpace(char *str,int length) {
char s[3];
s[0] = 'x';
s[1] = 'x';
s[2] = '\0';
//str=s;
std::strcpy(str,s);
std::cout << str << std::endl;
}
};

int main()
{
Solution sol;
char s[100] = "ss";
sol.replaceSpace(s, 2);
std::cout << s << std::endl;
return 0;
}
楼主是传入一个指针类,函数里是指针类的变动
所有(char*) str 会类似于(int)str
数组通过变量名赋值不会对内部的内容产生影响
只有改变内部的值