所以我写了一个代码来输入一个单词,把它的第一个字母放在单词的末尾(例如,“egg”将是“gge”,如果我们再次执行相同的过程,它将是“geg”,然后最后回到“egg”) 我只想执行此过程 1 次。而我想用一个指针来记住这个词的初值,也就是egg,然后字符串就得记住“gge”。
这是代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[100],aux,*P;
int p=1,i,n,k,j;
cin.get(s,100);
i=0;
while(i>=0)
{
P=s; //this is the pointer that SHOULD memorize "egg"
aux=s[0];
for(j=1; j<=n; j++) s[j-1]=s[j];
s[n]=aux;//until here it does the letter thing
break;
}
cout<<P<<endl<<s;//now here the pointer P should be "egg" and the string s should be "gge"
//but the program prints out "gge" and "gge".
return 0;
}
我做错了什么,我应该如何做我想做的事?
最佳答案
What am I doing wrong and how am I supposed to do what I want?
你好像误解了什么是指针。 指针是一个指向其他对象的变量。在这种情况下
char s[100];
char *P = s;
P
指向 s
的第一个字符元素。这与 s
在许多情况下衰减到的指针相同。
你仍然只有一个数组来存储 100 个字符。该数组只有两个标识符,因为您可以通过 s
或 P
访问它。
如果您将该数组从“egg”更改为“gge”或其他任何内容,P
仍然只指向它最初指向的同一个数组。除了位置(地址)之外,它没有保存任何内容的拷贝,而这并没有改变。
如果我可以走两条路到你的蓝房子,而你把房子重新粉刷成绿色,那么其中一条路不会仍然通向原来的蓝房子。这不是道路的运作方式、房屋的运作方式或指针的运作方式。
您想在某处存储原始的 3 或 4 个字符,这意味着您需要另一个字符数组,或者更好的 std::string
。这将在您更改字符之前复制您关心的字符。。
最小的工作变化可能是
// P = s <-- just stores the location
P = strdup(s); // <- copies the contents
但请注意,您应该在完成后的某个时候free(P)
。切换到 std::string
确实容易得多。
使用 std::string
值语义进行复制的简单示例:
#include <string>
#include <algorithm>
#include <iostream>
// source is a copy of the string passed
std::string rotate_left(std::string source, size_t offset = 1)
{
std::rotate(source.begin(), source.begin()+offset, source.end());
return source;
}
int main()
{
std::string original{"eggsoup"};
// for interactive use: getline(std::cin, original);
std::string rotated = rotate_left(original);
std::cout << original << '\n' << rotated << '\n';
}
关于c++ - 指针保留字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52951415/