Logan Cole
Logan Cole

Reputation: 1

Taking a 2D array and merging it into one

I am trying to figure out how to merge a 2D array into one.

I have a 2D array that looks as follows:

#include <stdio.h>

#define ROW 2
#define COL 10

int
main(void)
{
  int array[ROW][COL] = {2,6,12,18,23,55,57,58,59,60} , {1,3,5,9,11,19,27,28,31,56};
}

I was trying to use a nested for loop but wasn't having any luck.

Upvotes: 0

Views: 88

Answers (3)

lost_in_the_source
lost_in_the_source

Reputation: 11237

/* merge nbyA bytes of data in a with nbyB bytes of data in b. Return result. */
void *merge(const void *a, size_t nbyA, const void *b, size_t nbyB)
{
    void *buf = malloc(nbyA + nbyB);
    if (buf) {
        memcpy(buf, a, nbyA);
        memmove(buf + nbyA, b, nbyB);
    }

    return buf; /* caller must free */
}

To a pass array[0]; to b pass array[1].

The advantage of this solution is that you have a generalized merge function that can be used for more than just merging two subarrays of a 2D array, but for merging any two blocks of data.

Upvotes: 0

yhyrcanus
yhyrcanus

Reputation: 3813

memcpy isn't guaranteed to work. You're technically making an array of arrays, and depending on how the memory for each individual "linear" array is allocated, memcpy may or may not work. It likely will with the way you have it allocated, but it's not guaranteed.

This is what you were trying to do.

#include <stdio.h>

#define ROW 2
#define COL 10

int
main(void)
{
  int array[ROW][COL] ={ {2,6,12,18,23,55,57,58,59,60} , {1,3,5,9,11,19,27,28,31,56}};

  int i,j;

  int array1D[ROW*COL];

  for (i=0; i<ROW; i++){
        for (j=0; j<COL; j++){
            array1D[i*COL+j]=array[i][j];
        }
   }

   for (i=0; i<ROW*COL; i++){
      printf("%d ",array1D[i]);
   }

}

Note that here, i represents the row and j the column. To access an individual int and maintain the "2d" nature, the index would be row #*column length+column #. Or i*COL+j

Upvotes: 0

alk
alk

Reputation: 70893

Do this:

#include <string.h> /* for memcpy() */

#define ROW (2)
#define COL (10)

int main(void)
{
  int array[ROW][COL] = {
    {  2,  6, 12, 18, 23, 55, 57, 58, 59, 60}, 
    {  1,  3,  5,  9, 11, 19, 27, 28, 31, 56}
  };

  int array1D[ROW*COL];
  memcpy(array1D, array, ROW*COL * sizeof(int));
}

In C array elements are guaranteed to be placed in memory in a successive way (no padding!). So simply copying the memory should do.

Upvotes: 1

Related Questions