指针保留字符串

Pau*_*lP1 3 c++ string algorithm pointers

所以我写了一个输入一个单词的代码,把它的第一个字母放在单词的末尾(例如"egg"将是"gge",如果我们再次执行相同的过程,它将是"geg"和然后终于回到"鸡蛋")我想只做一次这个过程.我想用一个指针记住单词的初始值,即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;
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该怎么做我想要的?

Use*_*ess 6

我做错了什么,我该怎么做我想要的?

你似乎误解了指针是什么.指针是一个变量指向别的东西.在这种情况下

char s[100];
char *P = s;
Run Code Online (Sandbox Code Playgroud)

P 指向的第一个字符元素s.这是s在许多情况下衰减的指针.

您仍然只有一个数组来存储100个字符.你只需要该阵列两个标识符,因为你可以通过两种抵达它s还是P.

如果您将该数组从"egg"变为"gge"或其他任何位置,P仍然只是指向它最初所使用的相同数组.除了位置(地址)之外,它没有保存任何内容的副本,而这并没有改变.

如果我可以走两条路来到你的蓝色房子,你重新粉刷房子的绿色,其中一条道路仍然没有通往原来的蓝色房子.这不是道路如何运作,房屋如何运作,或指针如何运作.

你想在某个地方存储原始的3或4个字符,这意味着你想要另一个char数组,或者更好的a std::string.这将您更改之前复制您关注的字符.

可能是最小的工作变化

// P = s <-- just stores the location
P = strdup(s); // <- copies the contents
Run Code Online (Sandbox Code Playgroud)

但是请注意你应该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';
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我特此授权给任何需要解释指针并且不想用方框和箭头绘制图片的人. (2认同)