char* 的写权限

2022-01-12 00:00:00 char c++

简洁的问题:需要能够在c++中修改char*的内容.

Coincise question: Need to be able to modify contents of char* in c++.

我有一个有点像这样的函数:char* buffer = (char*)FUNCTION

I have a function which is somewhat like this: char* buffer = (char*)FUNCTION

现在我需要修改缓冲区",例如做这样的事情 buffer[1] = "h";

Now I need to modify 'buffer' e.g. do something like this buffer[1] = "h";

我尝试过的方法如下:char *string = "你好世界";字符缓冲区[65];//我仍然需要知道确切的大小strcpy(缓冲区,字符串);缓冲区[1] = "r";

Amongst what I have tried is the following: char *string = "Hello World"; char buffer[65]; //I still need to know the exact size strcpy(buffer, string); buffer[1] = "r";

我也尝试过使用 malloc.不幸的是,编译器总是抱怨以下内容:无法从 const char[2] 转换为 char".这发生在窗户上.我的g++编译器没有这样的问题.

I have tried with malloc also. Unfortunately, the compiler always complain with the following: "cannot convert from const char[2] to char". This occurs on windows. I do not have such a problem with g++ compiler.

我查看了以下链接,但仍然无能为力.http://www.developerweb.net/forum/archive/index.php/t-3517.html关于 C 中的字符指针是否可以在C?

I have had a looked at the following links but still I can't do anything. http://www.developerweb.net/forum/archive/index.php/t-3517.html About character pointers in C Is it possible to modify a string of char in C?

谢谢

推荐答案

由于您的问题被标记为 C++,我必须质疑您使用原始 char*s 的意图,除非您非常有信心,否则不建议这样做.

Since your question is tagged C++, I must question your intentions to be using raw char*s, it's not recommended unless you're very confident.

其次,char* 或 char[] 完全可以修改.您遇到的问题是您在Hello World"中创建了一个 const char*,然后试图使其中的一个字符等于一个字符串.字符不是字符串."r" 是一个字符串,它是一个 const char*.因此,您试图将 const char* 等同于 char,这是一个错误.你的意思是'r',它是一个字符.

Secondly, a char* or char[] is perfectly valid to modify. The problem that you've got is that you made a const char* in "Hello World", then tried to make one character in it equal to a string. A character is not a string. "r" is a string, it's a const char*. So you're trying to equate a const char* to a char, which is an error. You really mean 'r', which is a char.

更好的代码是:

std::string mystring((char*)FUNCTION); // assume that FUNCTION
                                       // will free it's own memory.
if (index < mystring.size())
    mystring[index] = 'r';
// mystring now cleans up it's own memory in all cases.

相关文章