设置结构中指针的值

Set the value of a pointer in a struct

本文关键字:指针 结构 设置      更新时间:2023-10-16

我有一个这样的结构:

typedef struct foo {
   int *bar;
   foo();
} foo;

并说一个这样的int:int i = 2;

如果我想使int* p1 = new int;指向i,我只需转到:p1 = &i;

如何使foo.bar指向i

我认为构造函数需要做以下工作:

foo::foo() {
   bar = new int;
}

但是我不知道如何使foo.bar指向i

在一个真实的例子中,你应该让构造器"foo(("初始化bar和一个删除它的dtor;这只是一个如何使用指向结构的指针访问成员的示例:

#include <iostream>
using namespace std;
typedef struct foo
{
    int* bar;
    foo(){}
}FOO, *PFOO;

int main(int argc, wchar_t *argv[])
{
    struct foo* ptrFoo = new foo;
//  PFOO pFoo = new foo; // you can use this also 
    ptrFoo->bar = new int(10);
    cout << ptrFoo->bar << endl;
    cout << (*ptrFoo).bar << endl;
    cout << *ptrFoo->bar << endl;
    cout << *(*ptrFoo).bar << endl;
    delete ptrFoo->bar;
    ptrFoo->bar = NULL;
    delete ptrFoo;
    ptrFoo = NULL;

    std::cin.get();
    return 0;
}

我已经解决了这个问题。

多人对内存泄漏的看法是正确的。

typedef struct foo {
        int *bar;
} foo;

尊重结构的指针成员:

int main() {
   foo fooIn;
   int i = 2;
   fooIn.bar = &i; // have the int pointer 'bar' point to the value i;
   int *barVal = (int*)fooIn.bar;
   printf("bar points to: %d, *barVal) // prints "bar points to: 2"

}