c++中使用数组的有效赋值

valid assign for use array in C++

本文关键字:有效 赋值 数组 c++      更新时间:2023-10-16

我想使用动态内存,但我不希望每次使用加上指针到特定位置。我总是用像

*(myPointer+position)

所以我想这样使用但我不知道这是否有效。

struct profile{
    double x;
    double y;
    int intencity;
};
profile *asdf;
profile asdfe;
asdf=new profile[1024];
///here is my problem
asdfe=asdf[myposition];

我的问题是这个{asdfe=asdf[myposition];}是否有效?

myPointer[position]等价于*(myPointer+position)

asdfe=asdf[myposition];

等价于

asdfe=*(asdf + myposition);

可以使用

asdfe=*asdf[mypostion]

尽管您可能希望确保asdf[myposition]首先是有效的。我可以建议创建一个测试应用程序来测试这个概念吗?指针的行为通常类似于数组,因此大多数编译器允许您以这种方式使用它们。

为了证明这个概念,你也可以使用

asdf[5] ->x = 7.3; //I made that up I don't have much context
asdf[5] ->y = 9.2;//That one too
asdf[5] ->intencity = 9001; //It's over 9000! Also it's spelled intensity.
asdfe=*asdf[5];
if(asdfe.x == 7.3)
    cout << "It worked!" << endl;

应该是这样的。据我所知。就像我说的,在一个测试应用程序上尝试一下,你可以自由地玩一些你不确定的东西。