simple pointer question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jakob Bieling

    #16
    Re: simple pointer question

    "lokman" <lokman@fagi.ne t> wrote in message
    news:c5t70i$n71 $1@nn-tk105.ocn.ad.jp ...[color=blue]
    > Hi and thanks for the great help.
    >
    > I have modified the simple code a little bit based on the reply.
    >
    > And I have a question again. I know that instead of using pointer
    > arithmetic, I can access individual characters in this way: e.g. cout <<
    > p[5]; This will simply print the 5th character in the character array.
    > (Correct me if I am wrong please.).[/color]

    It will actually print the 6th character .. p [0] prints the first, p
    [1] prints the second and so on
    [color=blue]
    > My question is: Can someone please tell me what is the reason that if I[/color]
    do:[color=blue]
    > cout << p[5] << endl; before the while loop, it prints the charater "p",[/color]
    as[color=blue]
    > expected. But somehow, after the while loop, if I do : cout << p[5] <<[/color]
    endl;[color=blue]
    > again, it cannot print the "p" character anymore.
    >
    > Thanks a lot again.
    >
    >
    > // Code starts below.
    > #include <iostream>
    >
    > using namespace::std;
    >
    > int main() {
    >
    > const char *p = "test pointer";
    >
    > cout << p[5] << endl; // New piece of code
    >
    > while (*p) { cout << *p; ++p;} // Modified ! I understand ++pp is a good[/color]

    Above you modifiy the pointer, ie the address it is pointing to.
    [color=blue]
    > practice now, thanks !!
    > cout << endl;
    >
    > cout << p[5] << endl; // New piece of code[/color]

    That means, that in the line above, p [5] means something different than
    the p [5] before the loop, because the value of p is different.
    [color=blue]
    > return 0;
    > }[/color]

    hth
    --
    jb

    (replace y with x if you want to reply by e-mail)


    Comment

    • Frane Roje

      #17
      Re: simple pointer question

      "Jakob Bieling" <netsurf@gmy.ne t> wrote in message
      news:c5s3km$je8 $07$1@news.t-online.com...
      [color=blue]
      > Now think about which values 's' and 't' will hold ..[/color]

      Yes I tried this code and it behaved correctly, I mean the out put
      is
      H e
      But then I didn't know what was the difference so I did a little bit
      different code:
      char test[]="Hello";

      char* p = test;

      char t = *p++;

      char s = (*p)++;

      char u = (*p)++;

      Now this outputs(remembe r the string is "Hello"):

      H e f

      So I was confused and did another test:

      char test[]="Hello";

      char* p = test;

      char t = (*p)++;

      char s = (*p)++;

      char u = (*p)++;

      And this outputs:

      H I J

      And I'm still confused, it seems like it outputs the alphabetically next
      character.

      I don't get it. Could someone clarify this?[color=blue]
      > Not necessarily in all implementations .[/color]
      So to be techically correct I should use size_t rather than unsigned int?

      --
      Frane Roje

      Have a nice day

      Remove (*dele*te) from email to reply


      Comment

      • lokman

        #18
        Re: simple pointer question

        Thanks !

        I now understand that: During the while loop, pointer p is keep on changing
        its memory address from the initial one which is point to character 't', up
        to '\0'. That is the reason why after the while loop, if I put the statement
        cout << p[5];, nothing will be return.

        In odder to have point p to point to the start of the "test pointer"
        characters, does it mean that I have to traverse p all the way back to where
        it is pointing to initially (doesn't seem to work as I tested and doesn't
        sound like a good practice) or should I reinitialize the p to point to "test
        pointer again" ?


        Actually, I have modified the previous code to become a version where I can
        guarantee to get char number 6 before and after the while loop, please give
        some comment.

        Thanks a lot.


        #include <iostream>

        using namespace::std;

        int main() {

        char chr[] = "test pointer";
        const char *p = chr; // constant character pointer to avoid chr[] content
        being change

        cout << p[5] << endl; // this prints p
        cout << chr[5] << endl; // this prints p too !

        while (*p) { cout << *p; ++p;}
        cout << endl;

        cout << chr[5] << endl; // this prints p after the while loop
        cout << p[5] << endl; // this doesn't print the 6th char anymore

        return 0;

        }





        "Jakob Bieling" <netsurf@gmy.ne t> wrote in message
        news:c5t8ce$2i4 $02$1@news.t-online.com...[color=blue]
        > "lokman" <lokman@fagi.ne t> wrote in message
        > news:c5t70i$n71 $1@nn-tk105.ocn.ad.jp ...[color=green]
        > > Hi and thanks for the great help.
        > >
        > > I have modified the simple code a little bit based on the reply.
        > >
        > > And I have a question again. I know that instead of using pointer
        > > arithmetic, I can access individual characters in this way: e.g. cout <<
        > > p[5]; This will simply print the 5th character in the character array.
        > > (Correct me if I am wrong please.).[/color]
        >
        > It will actually print the 6th character .. p [0] prints the first, p
        > [1] prints the second and so on
        >[color=green]
        > > My question is: Can someone please tell me what is the reason that if I[/color]
        > do:[color=green]
        > > cout << p[5] << endl; before the while loop, it prints the charater "p",[/color]
        > as[color=green]
        > > expected. But somehow, after the while loop, if I do : cout << p[5] <<[/color]
        > endl;[color=green]
        > > again, it cannot print the "p" character anymore.
        > >
        > > Thanks a lot again.
        > >
        > >
        > > // Code starts below.
        > > #include <iostream>
        > >
        > > using namespace::std;
        > >
        > > int main() {
        > >
        > > const char *p = "test pointer";
        > >
        > > cout << p[5] << endl; // New piece of code
        > >
        > > while (*p) { cout << *p; ++p;} // Modified ! I understand ++pp is a[/color][/color]
        good[color=blue]
        >
        > Above you modifiy the pointer, ie the address it is pointing to.
        >[color=green]
        > > practice now, thanks !!
        > > cout << endl;
        > >
        > > cout << p[5] << endl; // New piece of code[/color]
        >
        > That means, that in the line above, p [5] means something different[/color]
        than[color=blue]
        > the p [5] before the loop, because the value of p is different.
        >[color=green]
        > > return 0;
        > > }[/color]
        >
        > hth
        > --
        > jb
        >
        > (replace y with x if you want to reply by e-mail)
        >
        >[/color]


        Comment

        • David Riebenbauer

          #19
          Re: simple pointer question

          * Frane Roje <frane.roje@st. htnet.hr>:[color=blue]
          > "Jakob Bieling" <netsurf@gmy.ne t> wrote in message
          > news:c5s3km$je8 $07$1@news.t-online.com...
          >[color=green]
          >> Now think about which values 's' and 't' will hold ..[/color]
          >
          > Yes I tried this code and it behaved correctly, I mean the out put
          > is
          > H e
          > But then I didn't know what was the difference so I did a little bit
          > different code:[/color]
          Ok, so let's look at what this does exactly.
          [color=blue]
          > char test[]="Hello";
          >
          > char* p = test;[/color]
          Now p holds the address of the first char in test.[color=blue]
          >
          > char t = *p++;[/color]
          If you would have braces in here this would look something like this:
          char t = *(p++);
          First p is dereferenced and assigned to t.
          Afterwards p is incremented by the length of one char.
          So now it holds the address of the second char of test, which is 'e'.[color=blue]
          >
          > char s = (*p)++;[/color]
          As before first the value p points to is assigned to s.
          But now the value p points to is incremented, instead of p itself.
          So you modify test directly, which now holds "Hfllo".[color=blue]
          >
          > char u = (*p)++;[/color]
          Same as before but as test is modified yoiu get 'f';
          After this line test should be "Hgllo"[color=blue]
          >
          > Now this outputs(remembe r the string is "Hello"):
          >
          > H e f
          >
          > So I was confused and did another test:[/color]
          This should also become clear now.[color=blue]
          >
          > char test[]="Hello";
          >
          > char* p = test;
          >
          > char t = (*p)++;[/color]
          Iello[color=blue]
          >
          > char s = (*p)++;[/color]
          Jello[color=blue]
          >
          > char u = (*p)++;[/color]
          Kello[color=blue]
          >
          > And this outputs:
          >
          > H I J
          >
          > And I'm still confused, it seems like it outputs the alphabetically next
          > character.
          >
          > I don't get it. Could someone clarify this?[/color]
          Hope i succeeded.

          David

          --
          ,' David Riebenbauer - Student at Technichal University of Graz ~~~|
          /' / davrieb@sbox.tu graz.at /_,~""~""/ ICQ: 322056002 -\/- Playlist: |
          < /' Fernbedienung ~= Macht ,/'*','* '/ Die geht euch nichts an! |
          /\/\/\/\/\/\/\/\/\/\/\/\/\/' /)/(\ |/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

          Comment

          • Frane Roje

            #20
            Re: simple pointer question

            "David Riebenbauer" <davrieb@sbox.t ugraz.at> wrote in message
            news:40825ba7$0 $30786$3b214f66 @aconews.univie .ac.at...


            Yes you made it clear.
            It seems I've learned something wrong and it would be very bad if I hadn't
            found it now and then years later did.
            Anyway thanx

            --
            Frane Roje

            Have a nice day

            Remove (*dele*te) from email to reply


            Comment

            • Kevin Goodsell

              #21
              Re: simple pointer question

              David Riebenbauer wrote:
              [color=blue]
              > char t = *(p++);
              > First p is dereferenced and assigned to t.
              > Afterwards p is incremented by the length of one char.[/color]

              As I've mentioned a few times in this thread, this sequence of events is
              not required. In the expression 'p++' only the following is required:

              * The resulting value is equal to the value of the expression 'p' --
              that is, if you used 'p' instead of 'p++', the result would be the same,
              other than the side-effects.

              * As a side-effect, 'p' will be updated to point to the next character
              sometime before the next sequence point.

              There is no constraint on when the increment will occur, other than the
              requirement that it occurs before the next sequence point.

              -Kevin
              --
              My email address is valid, but changes periodically.
              To contact me please use the address from a recent posting.

              Comment

              • Kevin Goodsell

                #22
                Re: simple pointer question

                lokman wrote:
                [color=blue]
                > Thanks ![/color]

                Please stop top-posting, and trim the quoted text down to the relevant
                part. Read section 5 of the FAQ for posting guidelines.
                [color=blue]
                >
                > I now understand that: During the while loop, pointer p is keep on changing
                > its memory address from the initial one which is point to character 't', up
                > to '\0'. That is the reason why after the while loop, if I put the statement
                > cout << p[5];, nothing will be return.[/color]

                It's not accurate to say "nothing will be return". The behavior is
                undefined. You cannot wildly index past the end of an array.
                [color=blue]
                >
                > In odder to have point p to point to the start of the "test pointer"
                > characters, does it mean that I have to traverse p all the way back to where
                > it is pointing to initially (doesn't seem to work as I tested and doesn't
                > sound like a good practice) or should I reinitialize the p to point to "test
                > pointer again" ?[/color]

                If you iterate backward, how will you know when you've reached the
                beginning? The smart thing to do would be to save your original pointer
                if you still need it:

                const char * const the_string = "some literal";
                const char *p = the_string;

                // now use 'p' however you want

                p = the_string;

                You could reassign the same literal again, but 1) it's not guaranteed to
                be the same address and 2) duplicating parts of the code like that leads
                to problems later. When you change one, you have to be sure to change
                the other, and it's not obvious that the two are related.
                [color=blue]
                >
                >
                > Actually, I have modified the previous code to become a version where I can
                > guarantee to get char number 6 before and after the while loop, please give
                > some comment.
                >
                > Thanks a lot.
                >
                >
                > #include <iostream>
                >
                > using namespace::std;
                >
                > int main() {
                >
                > char chr[] = "test pointer";
                > const char *p = chr; // constant character pointer to avoid chr[] content
                > being change[/color]

                Just so we're clear, you don't *need* to have 'const' here -- that is,
                it would not be an error (from the language's point of view) if you
                modified the thing p points to. If it's not what you want your program
                to do, that's fine. But you could if you wanted to.
                [color=blue]
                >
                > cout << p[5] << endl; // this prints p
                > cout << chr[5] << endl; // this prints p too !
                >
                > while (*p) { cout << *p; ++p;}
                > cout << endl;
                >
                > cout << chr[5] << endl; // this prints p after the while loop
                > cout << p[5] << endl; // this doesn't print the 6th char anymore[/color]

                This gives undefined behavior.
                [color=blue]
                >
                > return 0;
                >
                > }
                >[/color]

                -Kevin
                --
                My email address is valid, but changes periodically.
                To contact me please use the address from a recent posting.

                Comment

                • David Riebenbauer

                  #23
                  Re: simple pointer question

                  * Kevin Goodsell <usenet2.spamfr ee.fusion@never box.com>:[color=blue]
                  > David Riebenbauer wrote:
                  >[color=green]
                  >> char t = *(p++);
                  >> First p is dereferenced and assigned to t.
                  >> Afterwards p is incremented by the length of one char.[/color]
                  >
                  > As I've mentioned a few times in this thread, this sequence of events is
                  > not required. In the expression 'p++' only the following is required:
                  >
                  > * The resulting value is equal to the value of the expression 'p' --
                  > that is, if you used 'p' instead of 'p++', the result would be the same,
                  > other than the side-effects.
                  >
                  > * As a side-effect, 'p' will be updated to point to the next character
                  > sometime before the next sequence point.
                  >
                  > There is no constraint on when the increment will occur, other than the
                  > requirement that it occurs before the next sequence point.[/color]

                  Ok, thanks for making this clear again.

                  David

                  --
                  ,' David Riebenbauer - Student at Technichal University of Graz ~~~|
                  /' / davrieb@sbox.tu graz.at /_,~""~""/ ICQ: 322056002 -\/- Playlist: |
                  < /' Fernbedienung ~= Macht ,/'*','* '/ Die geht euch nichts an! |
                  /\/\/\/\/\/\/\/\/\/\/\/\/\/' /)/(\ |/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

                  Comment

                  Working...