Thread: Flattening the array

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    9

    Flattening the array

    Hi guys,
    What do you think about "flattening the array"? Is this legal? For example:

    int matrix[6][10];
    int *mp;

    .....(some code goes here)


    mp = &matrix[3][8]; /* so mp points to 3rd row and 8th column */
    printf( "First element is %d\n",*mp);/* we are at [3][8]*/
    printf( "Second element is %d\n",*++mp);/* next one [3][9]*/
    printf( "Third element is %d\n",*++mp);/* [4][0] */

    Just read that this technique ia illegal and should be avoided.I don' t quite understand why.After all...aren't multi-dimensional array are really single-dimensional arrays?

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    16
    What exactly are you flattening?

    Looks to me like you are just referring to elements in the array with a 2nd pointer. Since the address and size of the array matrix is constant, then the array and all of its elements are safely bound to storage. Therefore I don't see anything wrong with this "flattening" at all.

    They probably are referring to dynamic arrays or something. Then there would be a danger of pointing your second pointer to freed memory and trying to dereference it(bad bad bad).

    Oh and yes, multi-dim arrays are really just one-dim arrays in mem.

  3. #3
    Sayeh
    Guest
    Multi dimensional arrays are _not_ just flat arrays in memory. In fact, it depends on the compiler, just exactly how they are assembled. That's why it's considered _illegal_, or atleast frowned upon.

    Multi-dimensional arrays are usually an array of pointers to the secondary dimension. More dimensions, more pointer layers.

  4. #4
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    You think you have it bad? We had to write a list flattening function in Lisp!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM