#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2012
    Posts
    7
    Rep Power
    0

    Talking Problem with pointer and 3D array


    Hi! Well I am just at the initial stage of programming world, so I am really stuck among addresses and dimensions. Means I am facing some problems with pointers and 3D array. Here is the problem

    Code:
    #include <stdio.h>
    
    int main ()
    {
         static int a[] = {0, 1, 2, 3, 4};
         static int *p[] = {a, a+2, a+1, a+4, a+3};
         int **ptr;
         ptr = p;
         **ptr;
         printf ("%d %d %d", **ptr, ptr-p, *ptr-a);
         return 0;
    }

    O/P is 2 1 2

    but according to concept I am holding about pointer and 3D array the output should have been 2 2 2. Did I miss something? I am expecting a lot of hopes. Thank you!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    Perhaps you should try again, with a more pedantic compiler.
    Code:
    $ gcc -W -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:9:6: warning: statement with no effect [-Wunused-value]
    foo.c:10:6: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat]
    foo.c:10:6: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘long int’ [-Wformat]
    $ ./a.out 
    0 0 0$
    > O/P is 2 1 2
    Output seems to depend entirely on the whim of the implementation, not the code written.

    I mean, to print the first 3 elements of the array, try say
    printf ("%d %d %d\n", **ptr, *(*ptr+1), *(*ptr+2));
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    156
    Rep Power
    34
    Originally Posted by kitebird
    ... I am facing some problems with pointers and 3D array
    You do not have 3D arrays anywhere in sight

    Here's a 3D array for comparison:
    [code=c]/* snippet */
    int a[2][6][4];

    a[0][1][2] = 42;
    a[1][5][3] = -1000;
    [/code]

    You might like to read the comp.lang.c FAQ. particularly section 6.

IMN logo majestic logo threadwatch logo seochat tools logo