通过指针分配给类内的数据

时间:2016-01-20 12:32:54

标签: c++

假设我们有类似的类型:

struct MyType
{
  OtherType* m_pfirst;
  OtherType* m_psecond;
  OtherType* m_pthird;

  ....
  OtherType* m_pn;
};

分配给会员是否安全?

MyType inst;
....
OtherType** pOther = &inst.m_pfirst;

for (int i = 0; i < numOfFields; ++i, ++pOther)
{
   *pOther = getAddr(i);
}

3 个答案:

答案 0 :(得分:1)

如果您的字段以这种方式命名,那么您别无选择:

inst.m_pFirst = getaddr(0);
inst.m_pSecond = getaddr(1);
...

更好的结构可能是:

struct MyType {
    OtherType *m_pFields[10];
}

...
for (int i=0; i<10; i++) {
    inst.m_pFields[i] = getaddr(i);
}

在标记C ++时,您可以使用ctor:

struct MyType {
    OtherType *m_pFirst;
    OtherType *m_pSecond;
    MyType(OtherType *p1,OtherType *p2): m_pFirst(p1), m_pSecond(p2) {};
};
...
MyType inst(getaddr(0),getaddr(1));

答案 1 :(得分:1)

*pOther = getAddr(i);

您在此处指定pOther的值而不是地址。 *正解除引用(访问指针内容)。而&则相反,获取指针或引用。

OtherType** pOther = &inst.m_pfirst;

这里&inst.m_pfirst首先.(prio.2)然后&(prio.3),所以你得到结构字段然后它的地址。 OtherType** pOther是指针上的指针。简而言之,您将内部指针更改为指向inst.m_pfirst。现在你可以自己说这是否有意义。

我实际上

struct mystruct {
int data;
char *arr;
};

struct mystruct *s = malloc(sizeof *s);
s->data = 5;  //same as (*s).data
int n = 3;
*(s->data) = &n; //now its 3
int capacity = s->data;
s->arr = malloc(capacity * sizeof(*(s->arr)))

然后你可以在适当的地方插入地址功能。

希望能稍微清理一下。

答案 2 :(得分:0)

这不是正确的方法。 impl->board[v1-1][v2].cout_of_things++ 会让你无处可去。此代码将产生未定义的行为。