Thread: arrays and pointers

  1. #1
    Registered User
    Join Date
    Oct 2001

    arrays and pointers

    may i ask what's the output of this code? what i got is 2 5 1 4.. but this doesn't seem to make any sense.

    const int MAXSIZE = 4;
    int data[ MAXSIZE ] = { 2, 5, 1, 4 };
    int count;

    for( count = 0; count < MAXSIZE; count++ )
    cout << *( data + count ) << " ";

  2. #2
    Registered User
    Join Date
    Dec 2001
    You haven't declared anything as a pointer. Try setting a pointer to the array, such as int *p=data and substituting p for data in the cout statement.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    What you got was correct for the code that you wrote. You accessed each element of the array through pointer notation and printed out the value. Arrays and pointers are similar, for example these two access statements are the same.
    The first is called subscript notation and the second is pointer notation, both work the same way because in this case pointers and arrays can be treated the same. Note that they can't be treated the same all of the time because they're not. Another way to write your code without the counter would be to declare a pointer and point it to the array
    int array[SIZE], *p = array[0];
    while(p < &array[SIZE])
        printf("%d", *p++);
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  2. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 04:49 PM
  3. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Help understanding arrays and pointers
    By James00 in forum C Programming
    Replies: 2
    Last Post: 05-27-2003, 01:41 AM