Pointer arithmatics and c style arrays

I am trying to improve my understanding of pointer. i know that there are smart pointers and vector/array containers in c++ now and i should use them as that would be the appropriate 'c++' way of doing things. But i am doing it the crude way for learning purposes.

In the following code, i am pointing a 'pointer' to a dynamically allocated array of size 5. I then try to place a character ('z') at each index of array and increment the pointer to make it point to next index.

In the second 'for' loop, i bring the pointer back 5 paces(to the start of the array)

In the third for loop, i simply display the values at eack index of the array by using pointer notation again.

The result that i am getting is incorrect. 'z' is displayed 20 times where as i think it should be 5 times as the array is of size 5. Can somebody explain the error. Debugging is not of much help to me.

Regards
Saherch


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

using namespace std;

///Using char * strings

int main()
{
    int array_size = 5;
    char * ptr;
    ptr = new char [array_size];

    for(int i = 0; i<array_size; ++i)
    {
        *ptr = 'z';
        ++ptr;
    }

    for(int j = 0; j<array_size; ++j)
    {
        cout<<--ptr;
    }

    for(int k = 0; k<array_size; ++k)
    {
        cout<<*ptr;
        ++ptr;
    }

    cout<<endl;

    return 0;
}
1
2
3
4
    for(int j = 0; j<array_size; ++j)
    {
        cout<<--ptr;
    }


Your printing here as well.
I've changed your code to make it more obvious what it's actually doing.
1
2
3
4
5
6
7
8
9
10
11
12
    char c = 'a';
    for(int i = 0; i<array_size; ++i)
    {
        *ptr = c+i;
        ++ptr;
    }

    for(int j = 0; j<array_size; ++j)
    {
        cout<<--ptr << endl;
    }


e
de
cde
bcde
abcde
a
b
c
d
e
Ohh that was so silly of me. I guess i was only paying attention to the pointers.

Many thanks for pointing that out.
Topic archived. No new replies allowed.