Thread: A pointer to multidim array element?

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    169

    A pointer to multidim array element?

    Just want to make sure Im not doing something completely wrong:

    Assume I have a two dimensional array:
    int array[MAXCOLS][MAXROWS];

    How do I declare and point a pointer to one of its elements? say array[1][2]

    Currently I have it set like this:
    int *p = &array[1][2];
    But I receive garbage.

    Thanks!

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Are you just printing the wrong thing? It works for me:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      int array[3][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9} };
      int *p = &array[1][2];
    
      printf("%d\n", *p);
    
      return 0;
    }
    My output:
    6
    If you understand what you're doing, you're not learning anything.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Define 'garbage'.
    Code:
    #include<stdio.h>
    
    int main( void )
    {
        int array[ 3 ][ 3 ] = 
        {
            { 0, 1, 2 },
            { 1, 2, 3 },
            { 2, 3, 4 },
        };
        int *p = &array[ 1 ][ 2 ];
    
        printf("*p is %d, array[ 1 ][ 2 ] is %d\n", *p, array[ 1 ][ 2 ] );
        return 0;
    }
    [edit]
    Curses, foiled again!
    [/edit]

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    169
    Haha yes, I was printing the wrong thing (&p instead of *p), I better watch out next time.
    Sorry about it and thanks alot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why does C need pointer conversion
    By password636 in forum C Programming
    Replies: 2
    Last Post: 04-10-2009, 07:33 AM
  2. pointer to first element in array
    By someprogr in forum C Programming
    Replies: 4
    Last Post: 01-10-2009, 02:52 AM
  3. sorting the matrix question..
    By transgalactic2 in forum C Programming
    Replies: 47
    Last Post: 12-22-2008, 03:17 PM
  4. Replies: 7
    Last Post: 11-25-2008, 01:50 AM
  5. Modify an single passed array element
    By swgh in forum C Programming
    Replies: 3
    Last Post: 08-04-2007, 08:58 AM