0

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;
}
blawien
  • 5
  • 4
  • 2
    Please ask your question explicitly. – mattm Apr 11 '20 at 13:32
  • 3
    What do you mean by "converting from 2d to 1d"? Can you please try to be more specific? And what is the real problem you need to solve? Why do you need to do this "converting"? Also please take some time to read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please [edit] your question to improve it. – Some programmer dude Apr 11 '20 at 13:33
  • 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 – blawien Apr 11 '20 at 13:38
  • 3
    It sounds like you want to flatten the array into a linear sequence of values, storing the result in a 1-dimensional array. Just iterate over the values as you're doing, and for each value `val`, do `flat_array[ix++] = val;` – Tom Karzes Apr 11 '20 at 13:41
  • i want to convert because my teacher gave some sample question and i am mixing questions and creating new weird question trying to practice and improve myself – blawien Apr 11 '20 at 13:41
  • 1
    To print out as a single line, or to store as a single array of `int` inside the program? For both those problems you basically have the code you need in the program you show (especially if all you want is to print it on a single line). To create an array to store the data in the program, first begin by creating the actual array. Then copy the values, one value at a time into the new array (using a loop just like the one you already have). – Some programmer dude Apr 11 '20 at 13:42
  • You can have a vector which is of same size as the 2-D array which you have. As you read the elements for your 2-D array, you can push that element into the vector also. This way you have the 1-D array which you need. – valarMorghulis Apr 11 '20 at 13:42
  • 1
    @YusufEkerdiker, there's effectively no difference between 2D and 1D arrays. – Ismael Luceno Apr 11 '20 at 16:45
  • 1
    Say you have `int p[3][3]={{1,2,3},{4,5,6},{7,8,9}};`; you can point to the same memory with `int *q=p[0];`, which you then can treat as a 9-item 1D array. – Ismael Luceno Apr 11 '20 at 16:51

2 Answers2

1
#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

choppe
  • 493
  • 2
  • 11
  • this is undefined behavior. See http://www.c-faq.com/aryptr/ary2dfunc2.html – tstanisl Aug 27 '21 at 10:00
  • I am not sure I am able to follow you on this ? May I get some clarifications please ? – choppe Aug 29 '21 at 01:42
  • Because the compiler perceives 'b[i]' as 'a[0][i]' what is UB for 'i' greater than 2 – tstanisl Aug 29 '21 at 06:40
  • @tstanisl, thanks a lot, it did bring in some sense to my little self, My assumption was that standard enforces continuous memory allocation for arrays. https://stackoverflow.com/questions/17125472/are-two-dimensional-arrays-in-c-required-to-make-all-elements-contiguous – choppe Aug 30 '21 at 01:13
1

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
Hitokiri
  • 3,607
  • 1
  • 9
  • 29
  • I didn't know is works in c too because i learned c++ first term and now learning c (i am so new at coding :/ ) – blawien Apr 11 '20 at 14:05
  • and i have 1 more question because i cant understand pointers. Do you know any youtube channel, documentation, book or anything else for pointers ? – blawien Apr 11 '20 at 14:07
  • https://www.geeksforgeeks.org/pointers-in-c-and-c-set-1-introduction-arithmetic-and-array/ maybe help – Hitokiri Apr 11 '20 at 14:12