Arrays and pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • justlearning
    New Member
    • Oct 2006
    • 2

    Arrays and pointers

    I have a problem that says modify a problem I have already done. but I have to use pointer notation instead of array notation. Could someone explain the difference to me.
  • m013690
    New Member
    • Sep 2006
    • 23

    #2
    to access a member in an array, you would use:

    array[ 4 ]

    to access the same item with pointer notation you could say:

    *( array + 4 )

    Comment

    • tyreld
      New Member
      • Sep 2006
      • 144

      #3
      Here is an illustrative example.

      Code:
      int array[4] = { 0, 1, 2, 3 };
      int *array_ptr1, *array_ptr2;
      
      // we assign array_ptr1 to the address for the first element.
      array_ptr1 = &array[0];  
      
      // C provides a shorthand for dealing with arrays. We can write the following
      // to accomplish the same task.
      array_ptr2 = array;
      
      if (array_ptr1 == array_ptr2)
        printf("This will always be true because both pointers contain the same value.\n");
      
      // Array indices are just doing pointer arithmetic in the background.
      printf("Value at index 2 via array index = %d\n", array[2]);
      printf("Value at index 2 via pointer addition = %d\n", *(array_ptr1 + 2));

      Comment

      Working...