char *的写权限 [英] Write permission for char*

查看:265
本文介绍了char *的写权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Coincise问题:需要能够在c ++中修改char *的内容。

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

我有一个类似这样的函数:char * buffer = *)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 =Hello World
char buffer [65]; //我还需要知道确切的大小
strcpy(buffer,string);
buffer [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。这发生在Windows上。
我没有这样的问题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 ++,我必须怀疑你使用原始字符的意图,除非你非常有信心,否则不建议。

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,这是一个错误。

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.

这篇关于char *的写权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆