简体   繁体   English

动态数组更改内存地址位置

[英]Dynamic array changing memory address locations

I'm having a slight issue and not quite understanding the syntax for what I'm wanting to do. 我有一个小问题,并不太了解我想要做的语法。 See below: 见下文:

float* ParticleSystem::GetMinLifeTime()
{
    return &minLifeTime;
}

I'm wanting to declare a dynamic array and then change the value of element 0 to point to the minLifeTime memory location. 我想声明一个动态数组,然后将元素0的值更改为指向minLifeTime内存位置。 MY attempt so far has been: 到目前为止,我的尝试是:

float* lifeTimeNumbers = new float[LIFETIME_STRINGS_SIZE];


lifeTimeNumbers[0] = *activeParticleSystem->GetMinLifeTime();

My understanding though is that I'm dereferencing the values when adding them to the array. 我的理解是,我在将它们添加到数组时取消引用这些值。 This isn't what I'm wanting. 这不是我想要的。 I'm really wanting to change the memory location of lifeTimeNumbers[0] to the memory location returned by GetMinLifeTime(). 我真的想将lifeTimeNumbers [0]的内存位置更改为GetMinLifeTime()返回的内存位置。 Can I do such a thing? 我能做这样的事吗?

Cheers 干杯

you can't change the address of [0] of the array as the array is basically ONE area of memory and not a number not individual pointers. 你不能改变数组[0]的地址,因为数组基本上是一个内存区域,而不是一个数字而不是单个指针。

Your 'isssue' could be done using a **.. then you could have [0] store a pointer to the value 您的“isssue”可以使用**来完成..然后您可以[0]存储指向该值的指针

Your question is mostly about how to fix the problems with an approach Y to achieving X. 您的问题主要是关于如何通过方法Y来解决问题以实现X.

Where approach Y is really meaningless (this is known as an XY-problem ). 方法Y实际上毫无意义(这被称为XY问题 )。

Instead of focusing on Y, do X directly: 而不是专注于Y,直接做X:

#include <vector>

double ParticleSystem::minLifeTime() const
{
    return minLifeTime_;
}

int main()
{
    std::vector<double> lifeTimeNumbers;

    ParticleSystem activeParticleSystem = ...;
    lifeTimeNumbers.push_back( activeParticleSystem.minLifeTime() );
}

I'm really wanting to change the memory location of lifeTimeNumbers[0] to the memory location returned by GetMinLifeTime() 我真的想将lifeTimeNumbers [0]的内存位置更改为GetMinLifeTime()返回的内存位置

All you need to do is this: 你需要做的就是:

float *lifeTimeNumbers = activeParticleSystem->GetMinLifetime();

Now you have a pointer which points to the first element of the array. 现在你有一个指向数组第一个元素的指针。

What you want is an array of pointers to floats rather than an array of floats. 你想要的是一个指向浮点数的指针数组,而不是一个浮点数组。 To achieve that you have to declare the array like this 要实现这一点,你必须像这样声明数组

float** lifeTimeNumbers = new float*[LIFETIME_STRINGS_SIZE];
lifeTimeNumbers[0] = activeParticleSystem->GetMinLifeTime();

but why not just using a vector container like this 但为什么不只是使用像这样的矢量容器

std::vector<float*> vec;
vec.push_back(activeParticleSystem->GetMinLifeTime());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM