[try Beta version]
Not logged in

 
 
pointer and arrays, while loop doesn't run?

Oct 10, 2015 at 8:52am
I'm practicing pointer and arrays. In the first source code the while loop works
and in the second source the while loop does not work. I don't understand why isn't pStart the same as pText?

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include <iostream>

using namespace std;

int main()
{

    string myarray[] = {"one","two","three"};
    string *pTexts = myarray;




    for (unsigned int i = 0; i < sizeof(myarray)/sizeof(string);i++)
    {

        cout << myarray[i] << " " << flush;

    }

    cout << endl;


    for(unsigned int i = 0; i < sizeof(myarray)/sizeof(string);i++)
    {
        cout << pTexts[i] << " " << flush;
    }

    cout << endl;

    for(unsigned int i = 0; i < sizeof(myarray)/sizeof(string); i++, pTexts++) {

        cout << *pTexts << " " <<flush;
    }


    string *pStart = &myarray[0];
    string *pEnd = &myarray[2];

 cout << endl;




    while(true) {

        cout << *pStart << " "  << flush; // *pTexts
        if(pStart == pEnd) { // pText
            break;
        }
        pStart++; // pText++

    }

    return 0;
}



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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>

using namespace std;

int main()
{

    string myarray[] = {"fuck","pussy","shit"};
    string *pTexts = myarray;




    for (unsigned int i = 0; i < sizeof(myarray)/sizeof(string);i++)
    {

        cout << myarray[i] << " " << flush;

    }

    cout << endl;


    for(unsigned int i = 0; i < sizeof(myarray)/sizeof(string);i++)
    {
        cout << pTexts[i] << " " << flush;
    }

    cout << endl;

    for(unsigned int i = 0; i < sizeof(myarray)/sizeof(string); i++, pTexts++) {

        cout << *pTexts << " " <<flush;
    }


    string *pStart = &myarray[0];
    string *pEnd = &myarray[2];

 cout << endl;




    while(true) {

        cout << *pTexts << " "  << flush; // *pTexts
        if(pTexts == pEnd) { // pText
            break;
        }
        pTexts++; // pText++

    }

    return 0;
}





Does it have anything to do with the fact that I already incremented pTexts in a for loop? in the second source.
I'm confused on why the first source code runs, while the second source doesn't.
To me these 2 while loops are equivalent. Please enlighten me on why this occurs.
Oct 10, 2015 at 11:03am
That is because in your second code after the third for loop pTesxt no longer points to myarray[0] instead it points to myarray[2], if you reassingned pointer pText to point to myarray[0] again your code should work fine.

You dont need pointer pStart so replace it with : pText = myarray;
Last edited on Oct 10, 2015 at 11:06am
Topic archived. No new replies allowed.