Search code examples
c++execution

Why my program executes before when it actually supposed to?


Okay here I have written a code, this program runs till the first while loop without executing the whole program. I have tied multiple ways like creating function, but facing the same problem.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str1, str2, temp;
    string *ptr1, *ptr2, *ptrtemp;
    int i, j;
    cout << "Enter string A: ";
    getline(cin, str1);
    cout << "Enter string B: ";
    getline(cin, str2);

    ptr1 = &str1;
    ptr2 = &str2;
    //swaping
    ptrtemp = ptr1;
    ptr1 = ptr2;
    ptr2 = ptrtemp;

    cout << "Now String A is= ";
    i = 0;
    while (i < str2.size())
    {
        cout << *ptr1;
        ptr1++;
        i++;
    }

    cout << "Now String B is= ";
    j = 0;
    while (j < str1.size())
    {
        cout << *ptr2;
        ptr2++;
        j++;
    }
    return 0;
}

Solution

  • string *ptr1, *ptr2, *ptrtemp;
    ...
        ptr1++;
    

    So, ptr1 points to a string. You then increment its value, which makes it point to some other string. But there is no other string for it to point to.

    I suspect you're thinking ptr1++; will somehow cause ptr1 to point to a different character in the same string. But it can't possibly do that. A string * can only point to a string, it cannot point to a character in a string.