I'm trying to write a function which yields (in the Python generator sense ... roughly speaking) elements of a 2D array one at a time in C. Each of these elements should be a pointer to the 0th value of a 1D subarray. I'm mystified why the code below doesn't work as expected.
#include <stdio.h>
void get_cords(int * coords){
static int count = 0;
int list[][2] = {{0,0}, {1,1}};
// this should assign the starting address of {0,0} to coords the first time the function is called, then the address of {1,1} next time
coords = list[count];
count +=1;
}
void main() {
int coords[] = {0,0};
get_cords(coords);
printf("%d, %d\n", coords[0], coords[1]);
get_cords(coords);
printf("%d, %d\n", coords[0], coords[1]);
}
Output:
0, 0
0, 0
Interestingly, if we assign the values individually in get_coords
, it works as expected:
void get_cords(int * coords){
static int count = 0;
int list[][2] = {{0,0}, {1,1}};
// this should assign the starting address of {0,0} to coords the first time the function is called, then the address of {1,1} next time
coords[0] = list[count][0];
coords[1] = list[count][1];
count +=1;
}
Expected and actual output:
0, 0
1, 1
Can someone explain what is going on here?