[英]Why my C code is giving me “segmentation fault” error when I try to read dynamically allocated array contents?
As the question explains, I'm creating a dynamically allocated array of structures(as i called, struct Desk*) in my C code. 正如问题所解释的,我正在C代码中创建一个动态分配的结构数组(如我所说的struct Desk *)。 In the main function, I am giving int id numbers in the "int deskId" fields of them .When I try to read their id's inside the main function, code works as expected.
在主函数中,我在它们的“ int deskId”字段中提供了int id号。当我尝试在主函数中读取其id时,代码将按预期工作。 On the other hand, if I try to read their id contents outside the main (as in the code below) it gives segmentation fault(core dumped) error.
另一方面,如果我尝试在主机之外读取它们的id内容(如下面的代码所示),则会出现分段错误(核心转储)错误。 I am giving the problematic code below.
我在下面给出有问题的代码。 As you see, I paid attention to give the address of the array parameter,(ie pointer to the actual array) so that i can read the actual content of the array, no the local copy.
如您所见,我注意提供了数组参数的地址(即指向实际数组的指针),以便可以读取数组的实际内容,而无需本地副本。 Thanks in advance.
提前致谢。
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
struct Desk {
int deskId;
Queue deskQueue;
};
struct TaxPayer {
int id; // tax payer ID
float duration; // payment duration
};
//function to display the ids of the desks
int display (int desks, struct Desk** argsptr) {
int i=0;
while(i < desks) {
printf ("My argument's id is %d\n",argsptr[i]->deskId );
i++;
}
return 0;
}
int main (int argc, char *argv[]) {
int option_index = 0;
int p_num = 20;
int desk_num = 4;
int max_q_size = 3;
//initialize array of desks
struct Desk* desk_array = malloc(desk_num * sizeof(struct Desk));
for (int i= 0; i < desk_num; i++) {
queueInit(&desk_array[i].deskQueue, sizeof(struct TaxPayer));
desk_array[i].deskId = i;
}
display(desk_num, &desk_array);
free(desk_array);
return 0;
}
You're passing the address of the desk_array
pointer to display()
rather than the pointer itself. 您正在将
desk_array
指针的地址传递给display()
而不是指针本身。 display()
is then reading the pointer, then the area of memory after the pointer, etc. What you want to do is pass the pointer desk_array
, and then use .
display()
然后读取指针,然后读取指针之后的内存区域,等等。您要做的是传递指针desk_array
,然后使用.
rather than ->
inside the function because the [i]
dereferences desk_array
. 而不是
->
在函数内部,因为[i]
取消引用了desk_array
。
int display (int desks, struct Desk* argsptr) {
int i=0;
while(i < desks) {
printf ("My argument's id is %d\n",argsptr[i].deskId );
i++;
}
return 0;
}
... ...
display(desk_num, desk_array);
argsptr[i]->deskId
accesses an array of struct Desk *
, but there is only one. argsptr[i]->deskId
访问struct Desk *
数组,但只有一个。 You need (*argsptr)[i].deskId
. 您需要
(*argsptr)[i].deskId
。
Alternatively, pass desk_array
instead of &desk_array
, change the parameter type to struct Desk *
, and use argsptr[i].deskId
. 或者,传递
desk_array
而不是&desk_array
,将参数类型更改为struct Desk *
,并使用argsptr[i].deskId
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.