'Flattening a 2D array in C without malloc etc
So I have been struggling with this for quit some time and I'm just not able to figure out how I'm supposed to flatten this randomly generated 5*15 2D array into a 1D and print it without using malloc but instead just for loops. And I'm slowly getting unhinged
This is the code for the printing random array.
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned short i, j;
int ar[5][15];
puts("The array: ");
for(i = 0; i < 5;i++) {
for(j = 0; j < 15;j++) {
printf("%d ", rand()%10);
}
printf("\n");
}
return 0;
}
Solution 1:[1]
If you just want to print them as if it's 1D-array just comment printf("\n"); in the outer for loop.
But, if you want the data from 2D-array in an 1D-array, you've to copy them individually.
#include <stdio.h>
#include <stdlib.h>
#define ROWS 5
#define COLS 15
int main() {
unsigned short i, j;
int ar[ROWS][COLS];
int flat_array [ROWS * COLS];
puts ("2D array: ");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
ar[i][j] = rand() % 10;
flat_array[COLS * i + j] = ar[i][j];
printf ("%d ", ar[i][j]);
}
printf ("\n");
}
printf("\nFlattened Array: \n");
for (int fi = 0; fi < ROWS * COLS; )
printf ("%d ", flat_array[fi++]);
return 0;
}
i.e. If you've a 2D array of size [M][N] and want to flatten it to an 1D array of size [M*N]
int Arr_2D[M][N]; // with data
int Arr_1D[M*N];
for (int ri = 0; ri < M; ++ri)
for (int ci = 0; ci < N; ++ci)
Arr_1D[ri * N + ci] = Arr_2D [ri][ci];
Also, Data in true-2D-array is stored in memory contiguously, as if a true-1D-array. So :
#include <stdio.h>
#include <stdlib.h>
#define ROWS 5
#define COLS 15
int main() {
int Arr_2D[ROWS][COLS];
printf ("Original 2D Array: \n");
for (int ri = 0; ri < ROWS; ++ri) {
for (int ci = 0; ci < COLS; ++ci) {
Arr_2D[ri][ci] = rand() % 10;
printf ("%d ", Arr_2D[ri][ci]);
}
printf ("\n");
}
printf ("\nAccessing a 2D array as 1D array: \n");
int *AP_1D = (int *) Arr_2D;
for (int ni =0; ni < ROWS * COLS; )
printf ("%d ", AP_1D[ni++]);
printf ("\n");
return 0;
}
There is also, Row & Column major memory storage, we digress.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
