指向结构和函数指针的指针 - > Seg 错误
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 %dn", 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 %dn", ret);
ret2 = reset(&test);
printf("reset returned with %dn", 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);
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- ``这个''不能用this-&gt;指针变量