I have a structure that represents a row in a table:
typedef struct {
char *a;
char *b;
} row;
and I have a function that initializes that row based on db data and returns a pointer to it
row* get_row(dbrow d) {
row *r = malloc(sizeof(row));
r->a = malloc(5);
strcpy(r->a, d.a);
r->b = malloc(5);
strcpy(r->b, d.b);
return r;
}
and finally, I have a function that has an row **rows as a parameter:
void get_rows(row **rows) {
...
rows = malloc(rowNumber * sizeof(row*));
int i;
for (i = 0; i < rowNumber; i++) {
rows[i] = get_row(dbrow);
}
}
get_row works as expected and returns a pointer to valid row struct, but gdb shows that rows[0] (and all the others) never gets a new value, that is, it always points to the same address, almost as if the rows[i] = get_row(dbrow) line doesn’t exist.
I’m assuming here that you are looking at the return value of your
get_rowsfunction, not at the value of its local variablerows. Here is the problem:You are assigning a new value to a copy of the original pointer that the function received, not the original. This change will not be visible outside the function.
If you need to assign a new value to the argument then you will need to add another level of indirection. Remember; everything in C is passed by value. So, your function should take a
row***as its argument:Also, as user1700513 pointed out, you are assigning a
row*to a row. That can’t be your actual code as it would result in a compiler error.