[英]Pointer to struct & function pointers -> Seg Fault
在執行此測試程序期間,我總是遇到分段錯誤。 我不知道為什么。 也許有人可以向我解釋一下,我確定我弄混了指針的內容。
#include <stdio.h>
struct xy {
int (*read)();
void (*write)(int);
};
struct z {
struct xy *st_xy;
};
static void write_val(int val)
{
printf("write %d\n", val);
}
static int read_val()
{
/* return something just for testing */
return 100;
}
int init(struct xy *cfg)
{
cfg->read = read_val;
cfg->write = write_val;
return 0;
}
int reset(struct z *st_z)
{
/* write something just for testing */
st_z->st_xy->write(111);
return 55;
}
int main(int argc, char **argv)
{
static struct z test;
int ret;
int ret2;
ret = init(test.st_xy);
printf("init returned with %d\n", ret);
ret2 = reset(&test);
printf("reset returned with %d\n", ret2);
return 0;
}
您永遠不會分配實際的xy
對象。 您的test.st_xy
只是一個垃圾指針,不允許您取消引用。
相反,請執行以下操作:
static struct z test;
static struct xy inner_test;
test.st_xy = &inner_test;
// ...
ret = init(test.st_xy);
您將指向xy的未初始化指針傳遞給init函數。
init(test.st_xy);
st_xy尚未初始化。 我認為沒有必要將st_xy用作指針。
struct z {
struct xy st_xy;
};
int main(int argc, char **argv)
{
static struct z test;
init(&test.st_xy);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.