5

我正在尝试将结构指针传递给函数并通过指针初始化结构。知道为什么这不起作用吗?

struct Re
{
    int length;
    int width;
};

void test (Re*);

int main()
{
    Re* blah = NULL;
    test(blah);
    cout << blah->width;
    return 0;
}

void test(Re *t) {
    t = new Re{5, 5};
}

我究竟做错了什么?

4

2 回答 2

12

指针被复制到函数中,因为它是按值传递的。您必须传递指向指针的指针或对指针的引用才能对其进行初始化:

void test(Re *&t) {
    t = new Re{5, 5};
}
于 2013-11-02T03:35:58.020 回答
1

您没有在函数参数中初始化指针,因为在您的test()函数中:

void test(Re *t) {
    t = new Re{5, 5};
}

您没有传递指针的引用。初始化指针对象需要指针的引用或指向指针的指针。

你也可以这样做:

int main()
{
    Re blah;
    test(&blah);
    cout << blah->width;
    return 0;
}

void test(Re *t) {

  t->length = 5;
  t->width = 5;    

};
于 2013-11-02T03:38:25.860 回答