指针数组声明
C++ Pointer array declaration
目前我有几个类的数组定义为'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;
- 在类c++中使用new声明数组
- 为什么不能用常量表达式声明数组?
- 声明数组后我无法添加数组
- 可以使用<size_t>static_const(),std::as_const()或static_cast<const size_t>()来声明数组吗?
- 变量未在此范围内声明 数组线性搜索
- 在类中声明数组. C++
- T D[N] 总是声明数组类型的对象吗?
- 如何使用智能指针在二维上声明数组?
- 声明数组>> int arr[] 时出错;在C++(虽然在 Java 中有效)?
- 在C 类中声明数组数据
- 声明数组时出现 SIGSEGV 错误,而不创建新的 int[size]
- 如何在不初始化常量的情况下声明数组?
- 使用函数在函数中声明数组值
- 以C++声明数组的时间复杂度
- 通过传递数组长度在函数内声明数组
- 通过引用传递数组,而不在函数声明中显式声明数组的大小
- 声明数组和打印[错误?]
- 用内核参数在CUDA内核中声明数组
- 如何在不依赖#Define的情况下转发声明数组大小
- 声明数组已经填充了零