Discussion:
[c-prog] stumped on 2 dimensional arrays
Bill Cunningham billcun@suddenlink.net [c-prog]
2018-11-03 20:23:08 UTC
Permalink
I have looked everywhere I know to look and can't get an answer on this
one. Here's the only code I know to try. Probably with bugs.

#include <stdio.h>

int main()
{
    char a[3][3] = { {}, {3, 2, 1} };
    int i, j;
    char b[3][3] = { {}, {} };
    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            b[j][j] = a[i][i];
}

I have a 2 dimensional array.First 3 element values not set. Second
initialize to 3,2, and 1. Can you copy one array value in a two
dimensional array to the other array? For example,

int a[3][3]; copy elements from the second array to the first that is
empty. Or has garbage values. There is memmove but I thought I might be
able to do this the manual way. Would I need to use another 2
dimensional array to do this?


Bill
jm5678@gmail.com [c-prog]
2018-11-03 20:49:52 UTC
Permalink
Arrays aren't 'objects' - you can't assign them whole, so you're stuck with memcpy etc. But you can wrap them in structs eg.
#include <stdio.h>


#define ARRAY_SZ(a) (sizeof(a) / sizeof(a[0]))


/* One row of array. */
typedef struct {
int col[4];
} row_t;


/* Whole array. */
typedef struct {
row_t row[3];
} array2d_t;


static void array2d_print(const array2d_t *array)
{
for (unsigned r = 0; r < ARRAY_SZ(array->row); r++) {
for (unsigned c = 0; c < ARRAY_SZ(array->row[r].col); c++)
printf(" %2d", array->row[r].col[c]);
printf("\n");
}
}


int main(void) {


array2d_t array = {{{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{9, 10, 11, 12}}}};
array2d_print(&array);


/* Swap rows 0 and 1. */
const row_t row = array.row[0];
array.row[0] = array.row[1];
array.row[1] = row;
printf("after swap:\n");
array2d_print(&array);


const array2d_t array2 = array;
printf("2nd array (copy):\n");
array2d_print(&array2);


return 0;
}


$ ./a.out
1 2 3 4
5 6 7 8
9 10 11 12
after swap:
5 6 7 8
1 2 3 4
9 10 11 12
2nd array (copy):
5 6 7 8
1 2 3 4
9 10 11 12



This allows you to assign rows and arrays, but not columns.

Loading...