[英]adding pointers to dynamic pointer array in a loop in c
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 我有一个函数,它基于db数据初始化该行并返回指向它的指针
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: 最后,我有一个函数, row **rows
作为参数:
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. get_row按预期工作并返回指向有效行结构的指针,但gdb显示rows [0](以及所有其他行)从不获取新值,也就是说,它总是指向相同的地址,几乎就像rows[i] = get_row(dbrow)
行不存在。
...gdb shows that rows[0] (and all the others) never gets a new value... ... gdb显示rows [0](和所有其他的)永远不会获得新值...
I'm assuming here that you are looking at the return value of your get_rows
function, not at the value of its local variable rows
. 我在这里假设您正在查看get_rows
函数的返回值,而不是其局部变量rows
的值。 Here is the problem: 这是问题所在:
rows = malloc(rowNumber * sizeof(row*));
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. C中的所有内容都按值传递。 So, your function should take a row***
as its argument: 所以,你的函数应该以row***
为参数:
void get_rows(row ***rows) {
if(!rows) {
signal_some_error();
return;
}
...
*rows = malloc(rowNumber * sizeof(row*));
...
}
Also, as user1700513 pointed out, you are assigning a row*
to a row. 此外,正如user1700513指出的那样,您正在为row*
分配row*
。 That can't be your actual code as it would result in a compiler error. 这可能不是您的实际代码,因为它会导致编译器错误。
change row r = malloc(sizeof(row));
改变row r = malloc(sizeof(row));
to row* r = malloc(sizeof(row));
to row* r = malloc(sizeof(row));
. 。 I am wondering why you didn't get a compiler warning for this. 我想知道你为什么没有得到编译器警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.