指针数组声明

C++ Pointer array declaration

本文关键字:声明 数组 指针      更新时间:2023-10-16

目前我有几个类的数组定义为'float myIDs'。我想将变量移动到父类中,并将其更改为指针('float * myIDs')。

目前我是这样声明它的值的:

float myIDs[] = {
    //Variables
};

由于它现在是一个指针,我认为它将大致相同:

myIDs = new float[] = {
};

但这似乎不起作用。我不确定如何解决这个问题,因为我从来没有像这样声明一个指针数组。

有谁能帮帮我吗?

谢谢

注意,你不是在分配一个指针数组,而是一个浮点数数组,所以基本上你的两个数组具有相同的类型,它们只是不会存储在相同的内存空间。

只有静态分配的数组可以这样初始化,动态分配的数组只能初始化为0。

myIDs = new float[]();

但是,如果您知道要放入数组的元素,则不需要动态地分配它。

如果你想分配指针的数组,你必须这样做:

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

但是只有静态分配的(第一个)可以用你描述的方式初始化,当然,它必须用指针初始化。

如果你想以动态的方式声明数组,你可以这样做:

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

当你不再需要内存时(例如在类析构函数中),请记住释放内存

delete [] array;

如果你想要一个动态分配的数组,你应该使用以下格式(你所做的看起来更像c#而不是c++)

//The declaration of the object in the class
float *myIDs;
//The allocation it self (you must know which size you want to allocate at this point)
myIDs = new float[size];//bring change "size" to whatever you need is.

考虑下面的代码片段,

#include<iostream>
#include<stdlib.h>
int main(void)
{
int a[] = {1,2};
a =new int[2];
delete(a);
return 0;
}

给出错误error: incompatible types in assignment of ‘int*’ to ‘int [2]’。我静态地创建了一个int数组。a是一个指针(类型为int[2]),但它不能用于指向其他动态分配的数组,因为它们返回类型为int*的指针。

如果你想动态创建一个数组,你必须将其地址分配给float*

float * a = new float[10] ;

最简单的方法是:

float *myArray[size];

例子
#include <iostream>
using namespace std;
float* findMax (float* myArray[], int size) {
    float max = 0;
    int index = 0;
    for (int i = 0; i < size; i++) {
        if ( *myArray[i] > max) {
            max = *myArray[i];
            index = i;
        }
    }
    
    return myArray[index];
}
int main()
{
    float a = 1.25; 
    float b = 2.47; 
    float c = 3.92; 
    float d = 4.67; 
    float e = 5.89; 
    float f = 6.01;
    
    float *myArray[6];
    int len = *(&myArray + 1) - myArray;
    myArray[0] = &a;
    myArray[1] = &b;
    myArray[2] = &c;
    myArray[3] = &d;
    myArray[4] = &e;
    myArray[5] = &f;
    cout << "Number of even values are : " << findMax(myArray, len) << endl;
    return 0;
}

如果你想要一个指针数组为float,你必须这样声明它。你只是声明了一个浮点数数组。数组的名称当然是一个指针,但在C语法中,它被视为相同的,只是为了方便。

float *myIDs[] = {
  //Variables
};
myIDs = new *float[n] = {
};

也可以使用

float **myIDs;
myIDs = new **float;

和访问数组的方式一样:

float *x = myIDs;