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.

40,024 questions

51,976 answers

573 users

How to map a 2D array element to a 1D array in C

1 Answer

0 votes
#include <stdio.h>

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

int set2DElementTo1D(int arr[], int row, int col, int value) {
    arr[row * COLS + col] = value;
}

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

    int arr[SIZE] = {0};
    set2DElementTo1D(arr, 1, 2, arr2d[1][2]);

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

    return 0;
}

 
/*
run:
 
0 0 0 0 0 0 8 0 0 0 0 0 
 
*/

 



answered Aug 14, 2024 by avibootz
edited Aug 14, 2024 by avibootz
...