C“ - >” (箭头算子)具有简单结构的Seg故障

时间:2013-10-23 04:09:24

标签: c segmentation-fault

我刚开始学习C大约一周前,我在使用箭头操作符“ - >”时遇到了一些问题。我尝试在线查找示例,但似乎没有任何帮助。这是一个简单的程序。

struct foo
{
    int x;
};

main(){
    struct foo t;
    struct foo* pt;

    t.x = 1;
    pt->x = 2; //here
}

当我使用gcc -o structTest structTest.c编译它并运行它时,我总是在标有注释“here”的行上得到分段错误。任何人都可以解释为什么会这样吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

您需要初始化pt以指向某事!现在它只是一个 null 未定义的指针。

尝试:

pt = &t;

例如。

答案 1 :(得分:3)

pt永远不会被初始化。

尝试添加pt = &t;

答案 2 :(得分:2)

您正在尝试取消引用尚未初始化的指针(指向您有权访问的内容)。

struct foo
{
    int x;
};

main(){
    struct foo t; // this is an instance of foo
    struct foo* pt; // this is a pointer to a foo

    t.x = 1; // you can set the contents of foo
    pt->x = 2; // you can't de-reference an un-initialized pointer
}

解决问题:

struct foo
{
    int x;
};

main(){
    struct foo t;
    struct foo* pt;

    t.x = 1;
    pt = &t; // make your pointer point to an instance of foo
    pt->x = 2; // this is ok now (this modifies the contents of 't')
}

答案 3 :(得分:1)

你必须把指针想象成一种两件事。第一部分是指针本身:

struct foo* pt;

指针的另一部分是它指向的东西。上面代码的问题是你的指针没有指向任何东西。

指针指向某物的方式是初始化它。有几种方法可以做到这一点。您的指针总是必须指向指针的目标类型的有效实例,然后才能取消引用它(使用 - >或*运算符)。

pt = new foo(); // one way to initialize your pointer by pointing it to newly allocated dynamic memory
pt = &t; // another way, by pointing it to the address of a local variable

void bar(foo *x)
{
    pt = x; // another way, by assigning it to another pointer
}

bar(new foo());

在初始化指针之前,它会悬空(一个“悬空指针”)。你不能取消引用它,因为它没有指向任何有效的东西。通常,如果你这样做,你的程序会崩溃,但它可以有许多其他有趣的行为。

要修复您的计划,您必须使pt指向有效的内容。我不知道你的计划最终目标是什么,所以你必须自己决定,但希望我已经给出了足够的线索。