Reputation: 5
I created a 2d array where the user can write the size (column and row) and fill it with random numbers, but I am having trouble converting from 2d to 1d. My question is how can i convert 2d array to 1d(like i am creating 3x3 array like this 92 88 4 next line 6 10 36 next line 96 66 83 and i want to convert it like 92 88 4 6 10 36 96 66 83). And if there is a problem with my code, please tell me. (Sorry for my grammatical errors)
This is my code;
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("Enter the number of rows: ");
int i;
scanf("%d", &i);
printf("Enter the number of columns: ");
int y;
scanf("%d", &y);
int array[i][y];
int rows, columns;
int random;
srand((unsigned)time(NULL));
for(rows=0;rows<i;rows++)
{
for(columns=0;columns<y;columns++)
{
random=rand()%100+1;
array[rows][columns] = random;
printf("%i\t",array[rows][columns]);
}
printf("\n");
}
return 0;
}
Upvotes: 0
Views: 3347
Reputation: 3689
Firstly, for time
function in srand((unsigned)time(NULL));
you need to include <time.h>
.
For storing value in 1D array, you just create an array with size = col * row
. In this example below, i allocate the int
pointer for saving all the values:
int * arr_1D = malloc(sizeof(int) * i * y);
if (arr_1D == NULL)
exit(-1);
The complete code for you (i just added something for convering 2D to 1D):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
printf("Enter the number of rows: ");
int i;
scanf("%d", &i);
printf("Enter the number of columns: ");
int y;
scanf("%d", &y);
int array[i][y];
int rows, columns;
int random;
srand((unsigned)time(NULL));
int * arr_1D = malloc(sizeof(int) * i * y);
if (arr_1D == NULL)
exit(-1);
int count = 0;
for(rows=0;rows<i;rows++)
{
for(columns=0;columns<y;columns++)
{
random=rand()%100+1;
array[rows][columns] = random;
printf("%i\t",array[rows][columns]);
// The code for converting 2D to 1D array
arr_1D[count++] = array[rows][columns];
}
printf("\n");
}
for (int k = 0; k < count; ++k)
{
printf("%d ", arr_1D[k]);
}
return 0;
}
result:
Enter the number of rows: 4
Enter the number of columns: 3
15 6 60
91 16 67
61 72 86
6 61 91
15 6 60 91 16 67 61 72 86 6 61 91
Upvotes: 1
Reputation: 506
#include <stdio.h>
int main()
{
int i = 0;
int a[3][3] = {{92,88,4},{6,10,36},{96,66,83}};
int *b;
b=&a[0][0];
for(i=0; i< 9; i++){
printf("%d\t", b[i]);
}
return 0;
}
This works because in C/C++ multidimensional arrays are stored continuously in memory. A good discussion could be found here
Upvotes: 1