[英]Pass pointer as reference to array
I'm trying to write a template function that utilizes the length of the array, given just the reference. 我正在尝试编写一个模板函数,该函数利用数组的长度(仅给出引用)。 I know the following code works 我知道以下代码有效
template <unsigned S>
void outputArray(int (&a)[S]) {
// S = length of array
}
int main() {
int a[6] = {0};
outputArray(a);
}
I am now attempting to expand upon this by using a dynamically allocated array. 我现在尝试通过使用动态分配的数组对此进行扩展。 I'm pretty sure this isn't possible given that the size of the array in the previous case was determined at compile time, but I could be wrong. 我很确定这是不可能的,因为前一种情况下数组的大小是在编译时确定的,但是我可能是错的。
void readFile(int*) {
int a_temp[MAX_DATA]; // MAX_DATA is predefined constant
int length;
// a_temp and length assigned from file
a = new int[length];
memcpy(a, &a_temp, sizeof(int)*length);
}
template <unsigned S>
void outputArray(int (&a)[S]) {}
int main() {
int* a;
readFile(a);
outputArray(a); // This is where my problem lies --- Mismatched types
}
Of course the irrelevant logic is truncated. 当然,不相关的逻辑会被截断。 As you can see in the readFile function, I am reading a variable length array from a file. 如您在readFile函数中看到的,我正在从文件中读取可变长度的数组。 However, I have no idea how to pass the array to the outputArray function as type int [S]
using the pointer. 但是,我不知道如何使用指针将数组作为int [S]
类型传递给outputArray函数。
I am restricted to using arrays (no C++ vectors) because this is a homework assignment. 我被限制使用数组(没有C ++向量),因为这是一项家庭作业。 If there is absolutely no way for me to pass the pointer as a type int [S]
then I will go down the route of simply having the readFile function return the value of the length of the array. 如果绝对没有办法将指针作为int [S]
类型传递,那么我将沿途简单地让readFile函数返回数组长度的值。
You can't do that. 你不能那样做。
C-style arrays carry no information about their length, and using C++ type constructs doesn't let you get around that fact. C风格的数组不包含有关其长度的信息,并且使用C ++类型的构造并不能解决这个问题。 If you want an array that knows its own length, you need to create your own data type, or better, use one of the standard container classes such as std::vector
. 如果您想要一个知道自己长度的数组,则需要创建自己的数据类型,或者更好的方法是使用标准容器类之一,例如std::vector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.