Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to convert a 2D array to a 1D array in C

2 Answers

0 votes
#include <stdio.h>
 
#define SIZE 3
 
void arr2DTo1D(int arr2d[][3], int rows, int cols, int arr[]) {
    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr[k++] = arr2d[i][j];
        }
    }
}
 
int main() {
    int arr2d[SIZE][SIZE] = { 
        { 5, 6, 1 }, 
        { 3, 8, 0 },
        { 9, 2, 7 } 
    };
 
    int arr[SIZE * SIZE];
    arr2DTo1D(arr2d, SIZE, SIZE, arr);
 
    for (int i = 0; i < SIZE * SIZE; i++) {
        printf("%d ", arr[i]);
    }
 
    return 0;
}
 
 
  
/*
run:
  
5 6 1 3 8 0 9 2 7 
  
*/

 



answered Aug 14, 2024 by avibootz
edited Oct 11, 2024 by avibootz
0 votes
#include <stdio.h>

#define ROWS 3
#define COLS 4
#define SIZE ROWS * COLS

void arr2DTo1D(int arr2d[][COLS], int rows, int cols, int arr[]) {
    int k = 0;
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr[k++] = arr2d[i][j];
        }
    }
}

int main() {
    int arr2d[ROWS][COLS] = { 
        { 5, 6, 1, 4 }, 
        { 3, 8, 0, 2 },
        { 9, 2, 7, 1 } 
    };

    int arr[SIZE];
    arr2DTo1D(arr2d, ROWS, COLS, arr);

    for (int i = 0; i < SIZE; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}


 
/*
run:
 
5 6 1 4 3 8 0 2 9 2 7 1 
 
*/

 



answered Aug 14, 2024 by avibootz

Related questions

1 answer 136 views
1 answer 142 views
1 answer 80 views
80 views asked Dec 3, 2024 by avibootz
1 answer 91 views
1 answer 91 views
1 answer 79 views
2 answers 112 views
...