2016-09-30 67 views
-4

我有一個結構,像這樣:設置一個指針的值在結構

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

,並說一個int像這樣:int i = 2;

如果我想提出int* p1 = new int;i我只是去:p1 = &i;

我如何foo.bari

我想構造需要做到以下幾點:

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

但我不知道如何使foo.bari

+2

這絕對不是C.功能作爲一個結構內的構件在C. –

+0

'foo-無效> bar =&i;' –

+1

這是C還是C++的問題?因爲你的結構是用C編寫的,而'new'關鍵字是C++。 – plasmacel

回答

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" 

}

0

在一個真實的例子中,你應該讓construtor「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; 
}