Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer array declaration

Currently I have a several classes with an array defined as 'float myIDs'. I want to move the variable into my parent class and change it to a pointer ('float * myIDs').

Currently I'm declaring its values like this:

float myIDs[] = {
    //Variables
};

As its now a pointer, I thought that it would be roughly the same:

myIDs = new float[] = {
};

but that doesnt seem to be working. I'm not sure how to solve this as I've never had to declare a pointer array like this before.

Can anyone help me please?

Thanks

like image 391
Split Avatar asked Sep 23 '26 19:09

Split


2 Answers

Note that you're not allocating an array of pointer but just an array of float, so basically you two array would have the same type, they just won't be stored in the same memory space.

Only a statically allocated array can be initialized this way, a dynamically allocated one cannot be initialized to anything other than zero.

myIDs = new float[]();

But if you know the elements to put in the array, you don't need to allocate it dynamically.

If you want to allocate an array of pointer, you have to do this :

float* myIDs[size]; // statically
float** myIDs = new float*[size]; // dynamically

But only the statically allocated one (the first one) can be initialized the way you describe and of course, it must be initialized with pointers.

like image 157
zakinster Avatar answered Sep 25 '26 08:09

zakinster


If you want to declare array in a dynamic way, you can do it like this:

float *array = new float[size];
array[0] = first_value;
array[1] = second_value;
etc; 

Just remember to free memory when you no longer need it (e.g. in a class destructor)

delete [] array;
like image 30
Tomasz Avatar answered Sep 25 '26 10:09

Tomasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!