Pointer arithmitic

So this is a pretty basic question but it had me thinking so I guess I will go ahead and ask it

so with my code as the example below I created three strings and three pointers to the strings but I just used the first pointer and incremented it but I get weird results,I expected something different to my surprise when I incremented p1 the first time and dereferenced it,it printed out the second string then again I incremented the pointer and dereferenced it and it printed the next string

the reason why I am surprised is that the strings are not in an array,so shouldn't they be in different memory locations and not in contiguous locations like an array?

or is this just by chance that this is happening?



hello
hey
heyo




thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  using namespace std;

int main()
{
    string hello = "hello";
    string hey = "hey";
    string heyo = "heyo";


    string* p1 = &hello;
    string* p2 = &hey;
    string* p3 = &heyo;

    cout << *p1 << endl;
    p1++;
    cout << *p1 << endl;
    p1++;
    cout << *p1 << endl;
    p1++;
}
Last edited on
> or is this just by chance that this is happening?

Yes. The program has undefined behaviour.
Registered users can post here. Sign in or register to post.