I am trying to wrap my head about the concept of 2-dimensional arrays (of structs) in C
Say I have the following definition:
typedef struct group group;
struct group {
int members;
int neighbours;
char color;
};
#define NUM_CELLS 10
With the following function that is supposed to copy some data from a single array to a multidimensional array:
void test_mgroup_arr(group clusters[][NUM_CELLS],group tests[NUM_CELLS], int num_groups) {
int i;
int j = 0;
for (i = 0; i < num_groups; ++i)
clusters[i][j] = tests[i];
}
This is called like:
int num_groups = 5;
group clusters[NUM_CELLS][NUM_CELLS];
group tests[NUM_CELLS];
tests[0].members = 101;
tests[0].neighbours = 111;
tests[1].members = 102;
tests[1].neighbours = 112;
tests[2].members = 103;
tests[2].neighbours = 113;
tests[3].members = 104;
tests[3].neighbours = 114;
tests[4] = tests[3];
test_mgroup_arr(clusters, tests, num_groups);
I expect the code in the function to copy the 5 items from the test array to the right place in the multi-dimensional array. However, this does not work as expected, and even segfaults in some cases.
How is this not correct? What would be the right way of copying a struct from a 1dim array to a 2 dim array?
I expect the code in the function to copy the 5 items from the test array to the right place in the multi-dimensional array.define "right place". If you want test[n] == clusters[n][0], then you're doing it right. If you want test[n] == clusters[0][n] then yourtest_mgroup_arr()is backwards