[英]Set the value of a pointer in a struct
我有一个像这样的结构:
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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.