pyp*_*ies 2 c++ pointers readonly segmentation-fault
在阅读了faq和我能找到的其他所有内容后,我仍然感到困惑.如果我有一个以这种方式初始化的char指针:
char *s = "Hello world!"
字符串在只读内存中,我无法像这样更改它:
*s = 'W';
Run Code Online (Sandbox Code Playgroud)
制作"Wello世界!".我理解这一点,但对于我的生活,我不能理解如何使它不是只读的.我必须使用数组而不是指针吗?喜欢这里?
这是我的代码:
char *s = str;
char *e = s;
while (*e != '\0')
e++;
e--;
char *temp;
//Swop the string around
while (s <= e) {
*temp = *s;
*s = *e;
*e = *temp;
e--;
s++;
}
Run Code Online (Sandbox Code Playgroud)
错误消息只是一个分段错误.如果这是一个非常愚蠢的问题,请提前道歉.
非常感谢所有的帮助.在接受了你的所有建议后,我得到了这个:
void something(char * str) {
char *store = str;
char *s = new char[strlen(str) + 1]; //Allocate memory. Nice one.
strcpy(s, str);
char *e = new char[strlen(str) + 1];
strcpy(e, str);
while (*e != '\0')
e++;
e--;
char temp; //no longer a pointer
while (s <= e) {
cout << *e;
temp = *s;
*s = *e;
*e = temp;
e--;
s++;
}
delete [] e;
delete [] s;
}
Run Code Online (Sandbox Code Playgroud)
但是,函数末尾的删除似乎导致了它们自己的分段错误.为什么?
为了感兴趣:故障是由于在增加后访问e和s指针.一个更简单的解决方案:
void something(char * str) {
char *s = new char[strlen(str) + 1];
strcpy(s, str);
char temp;
int j = strlen(str) - 1;
for (int i = 0; i <= strlen(str)/2; i++) {
cout << s << endl;
temp = s[i];
s[i] = s[j];
s[j] = temp;
j--;
}
delete [] s;
}
Run Code Online (Sandbox Code Playgroud)
尝试:
char src[] = "Hello world";
src[6] = 'W';
-- // or
char buffer[] = "Hello world";
char* src = buffer;
src[6] = 'W';
Run Code Online (Sandbox Code Playgroud)
如果要将字符串复制到缓冲区中,请使用strcpy()或strncpy()
char buffer[20];
char const* s = "Hello World"
strcpy(s,buffer);
Run Code Online (Sandbox Code Playgroud)
如果你必须编写自己的字符串副本,那么它应该如下所示:
char buffer[20];
char const* s = "Hello World";
// OK this is not the perfect solution but it is easy to read.
for(int loop = 0;s[loop] != '\0';++loop)
{
buffer[loop] = s[loop];
}
buffer[loop] = '\0';
Run Code Online (Sandbox Code Playgroud)
修改它的最简单方法是为存储创建一个数组,然后将字符串复制到其中.
例如:
char buf[128];
const char *src = "Hello World";
strncpy(buf, src, 127); // one less - we always 0-terminate
buf[127] = '\0';
// you can now modify buf
buf[0] = 'W';
Run Code Online (Sandbox Code Playgroud)
您的代码不起作用的原因是您没有为字符串的副本分配任何内存 - 您刚刚创建了指向同一只读内存的第二个指针.(然后尝试复制它?我不太确定代码的其余部分是做什么的.)你需要在某处获得一些非只读内存,并且使用标准库将其复制到那个新的记忆,而不是自己写的循环.
如果你事先不知道字符串的长度,你也可以使用malloc(或者更好的是,做drschnz的答案并使用新的char []):
const char *src = "Hello world";
char *buf = malloc(strlen(src) + 1); // or = new char[strlen(src) + 1];
strcpy(buf, src);
// you can now modify buf
// later, you need to free it
free(buf); // or delete [] buf;
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用的是C++,则可以使用std :: string:
std::string myString("Hello world");
myString[0] = "W";
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
4568 次 |
| 最近记录: |