Thread: Double pointer & Two Dimensional Array

  1. #1
    Registered User
    Join Date
    Nov 2009

    Double pointer & Two Dimensional Array

    Why Below Program Produces Segmentation error

    void print_arr(float **p)
    printf(" 0 %f 1 %f 2 %f\n",p[0][0],p[0][1],p[0][2]);
    void main()
    float arr[2][3] = {{0,1,2},{3,4,5}};
    float **fl_arr;
    fl_arr = (float *)arr;

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    A pointer to a pointer isn't the same as a two dimensional array. Compile with warnings on.

    Read: Arrays and Pointers

    Hope is the first step on the road to disappointment.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    fl_arr is a pointer to a pointer, but it only has space for one address.

    Segmentation fault - Wikipedia, the free encyclopedia

    You are referencing memory that does not exist when you refer to members of p in print_arr(). fl_arr does not have members, so p has an address, but p[0] does not.

    arr is not a pointer. It is an array. You could refer to the address of a:
    fl_arr = &arr;
    In which case the compiler will warn you of an incompatible type.

    fl_arr must itself be an array in order to be used as one.
    float *fl_arr[2] = {arr[0],arr[1]};
    Now it is an array of two pointers, which the higher dimensions of multi-dimensional arrays can be considered pointers and arrays of pointers.

    You cannot do this with a pointer array tho:
    Now it has members you have to refer to them. fl_arr[0]++ is allowed, but will not have the effect I think you intend.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double Pointer & Two Dimension Array ....
    By gokulvs in forum C Programming
    Replies: 7
    Last Post: 09-09-2009, 11:04 PM
  2. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  3. double pointer to 2-dim array?
    By vex_helix in forum C Programming
    Replies: 2
    Last Post: 04-06-2004, 12:31 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM