为什么我会为以下代码获取分段错误? [英] Why Do I Get Segmentation Fault For The Below Code?

查看:59
本文介绍了为什么我会为以下代码获取分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef struct {

int a;

int c;

} s1;



typedef struct {

int b;

} s2;



typedef const struct {

s1 * ptr1;

s2 * ptr2;

} M;

静态实例;

void main()

{

stinstance.ptr1-> a = 10;

printf(%x ,stinstance.ptr1);

}

解决方案

因为M的成员ptr1和ptr2是指针,尚未初始化 - 所以它们目前包含随机值



指针是事物的地址 - 这些东西需要分配或已经存在,才能使用它们的地址



指针初学者指南 [ ^

typedef struct {
int a;
int c;
}s1;

typedef struct {
int b;
}s2;

typedef const struct {
s1 *ptr1;
s2 *ptr2;
}M;
static M stinstance;
void main()
{
stinstance.ptr1->a = 10;
printf("%x",stinstance.ptr1);
}

解决方案

Because the members ptr1 and ptr2 of M are pointers, that haven't been initialised - so they currently contain random values

pointers are addresses to things - those things need to be allocated, or already existing, before their address can be used

A Beginner's Guide to Pointers[^]


这篇关于为什么我会为以下代码获取分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆