I was browsing a question and found this answer.
I couldnt understand this program at the end of the answer,
Specifically the first three lines of the putoff function
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_ELEM(ar) (sizeof(ar) / sizeof((ar)[0]))
int * put_off(const int newrow[2])
{
static int mymatrix[3][2];
static int (*rowp)[2] = mymatrix;
int (* const border)[] = mymatrix + NUM_ELEM(mymatrix);
memcpy(rowp, newrow, sizeof(*rowp));
rowp += 1;
if (rowp == border) {
rowp = mymatrix;
}
return *rowp;
}
int main(int argc, char *argv[])
{
int i = 0;
int row[2] = {0, 1};
int *rout;
for (i = 0; i < 6; i++) {
row[0] = i;
row[1] += i;
rout = put_off(row);
printf("%d (%p): [%d, %d]\n", i, (void *) rout, rout[0], rout[1]);
}
return 0;
}
I need some help with the first 3 lines in the function in the program.
Here are some explanatory notes to get you going:
mymatrixis a 2D array of ints with 3 rows and 2 columns. C uses row-major order, meaning the rows are stored one after the other in memory. The static keyword makes its values persistent across function calls (while the scope is still local).This declares a pointer to array of two integers (i.e., a row of mymatrix in this case). Initializing it to mymatrix is the equivalent of initializing it to the first row. The static keyword of course means the same as above.
borderis a constant pointer (i.e., the pointer can’t be changed) to an array of ints. It is initialized to a memory address beyond mymatrix (which is maybe a tad unusual). Specifically, it points to the next row that would exist ifmymatrixhad one more row, so when the row pointer points to exactly that spot, the function wraps around the row pointer back to the first row having filled the entire matrix.For conglomerations of pointers, arrays parentheses, etc., you can always try cdecl to see if it can translate it for you.