Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Where is my mistake following this code

  1. Oct 18, 2008 #1
    next to every line i commented on what i think it does

    where is my mistake in understanding of changing the index of the pointer
    ??
    Code (Text):


    #include <stdio.h>

    int main() {
      int *ptr;
      int arrayInts[10] = {1,2,3,4,5,6,7,8,9,10};

      ptr = arrayInts;                                           //ptr points at cell [0]=1
      printf("The pointer is pointing to the first ");    
      printf("array element, which is %d.\n", *ptr);   //print 1
      printf("Let's increment it.....\n");  

      ptr++;                                                         //ptr points at cell [1]=2

      printf("Now it should point to the next element,");
      printf(" which is %d.\n", *ptr);                                                      //print 2
      printf("But suppose we point to the 3rd and 4th: %d %d.\n",     // print cells [2] [3] 3 4
              *(ptr+1),*(ptr+2));                                                               //ptr stays the same

      ptr+=2;                                                                         /ptr points at cell [3]=4

      printf("Now skip the next 4 to point to the 8th: %d.\n",
              *(ptr+=4));                                                            //ptr points to cell[8]=9
                                                                                          //and we print the new ptr
     
    ptr--;                                                                             //ptr points to cell[7]=8

      printf("Did I miss out my lucky number %d?!\n", *(ptr++));     //ptr points to cell[8]=9
                                                                                                        //and prints it

      printf("Back to the 8th it is then..... %d.\n", *ptr);                //ptr points to cell[8]=9
                                                                                                         //and prints it

      return 0;
    }

     
     
  2. jcsd
  3. Oct 19, 2008 #2
    Do you notice anything strange about the line

    Code (Text):

    printf("Now skip the next 4 to point to the 8th: %d.\n",
              *(ptr+=4));                                                            //ptr points to cell[8]=9
     
    In particular, is your comment on this line really correct?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Where is my mistake following this code
  1. Critique my C++ code (Replies: 11)

Loading...