设置结构中指针的值
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"
}
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 指针或结构的矢量
- MSVC将仅移动结构参数解释为指针
- 如何访问指针结构的成员变量?
- 如何将变量从变量传递到指针结构对象
- 如何在函数中检索指针结构
- C :变量的点地址至指针结构成员的地址
- C++指针结构不会被删除
- 初始化指针结构 - 内存中的外观
- C++指针结构和多线程
- c++中指针结构的运算符重载
- 为什么我不能转发声明指针结构?
- C# 如何定义新的指针结构
- 如何处理大型指针结构
- 我怎么能写一个函数的定义在模板类中声明返回指针结构对象
- 我如何编程指针结构或类变量在c++
- 具有指针结构的类所需的析构函数
- 为什么在非指针结构上进行类型转换会出现语法错误
- 语法:做binary_search (STL)排序向量的指针结构
- /a.检测到Glibc.out: munmap_chunk():无效指针- c++结构体的动态数组