C++ 返回指针问题
我正在尝试复制阵列的副本,但新副本的顺序必须相反。我的问题是我的C++ 返回指针问题,c++,pointers,C++,Pointers,我正在尝试复制阵列的副本,但新副本的顺序必须相反。我的问题是我的reverse函数,我评论了错误说明的内容,我不明白的是为什么它会这样说?如果copy是指针变量?我仍然在与指针作斗争,我真的只是想澄清一下我做错了什么。我还没有做一个反向指针变量,我计划在我弄清楚为什么会出现这个错误后再做 下面是函数 int* reverse(int elements, int size) { int* copy = new int [size]; int k =0; for(int j=
reverse
函数,我评论了错误说明的内容,我不明白的是为什么它会这样说?如果copy是指针变量?我仍然在与指针作斗争,我真的只是想澄清一下我做错了什么。我还没有做一个反向指针变量,我计划在我弄清楚为什么会出现这个错误后再做
下面是函数
int* reverse(int elements, int size)
{
int* copy = new int [size];
int k =0;
for(int j=size-1; j >=0;j--)
{
copy[k] = size[j]; // Error-> Subscripted value is not an array,pointer or vector
k++;
}
return copy;
}
这是没有函数的完整代码
#include <iostream>
int* allocation(int);
void output(int*, int);
int* reverse(int*, int);
int main()
{
int size;
std::cout << "Enter the size you want to allocate" << std::endl;
std::cin >> size;
int* array = allocation(size);
std::cout << "Displays the elements of the array";
output(array,size);
return 0;
}
void output(int* array, int size)
{
for(int k=0;k<size;k++)
{
std::cout << " " << array[k];
}
}
int* allocation(int elements)
{
int* ptr = new int[elements];
std::cout << "Enter the elements for size of array." << std::endl;
for(int i =0; i < elements; i++)
{
std:: cin >> ptr[i];
}
return ptr;
}
#包括
整数*分配(整数);
无效输出(int*,int);
int*反向(int*,int);
int main()
{
整数大小;
标准:cout大小;
int*数组=分配(大小);
std::cout您的reverse
函数的问题在于,您没有将指针传递到源数组,而必须以相反的顺序进行复制。相反,您传递了两个int
s
错误
错误->下标值不是数组、指针或向量
当您尝试使用size
作为数组时,通过向其添加下标size[j]
发生这种情况,因为size
是int
类型,而不是指针、数组或向量
我已将您的函数签名从
int* reverse(int elements, int size)
到
我修改了你的函数,使其看起来像这样
int* reverse(int *elements, int size)
{
int* copy = new int [size];
for(int j=size-1, k=0; j >=0; j--, k++)
{
// copy from elements and not size, elements is the array containing
// the values to be copied, size denotes the size of the array
copy[k] = elements[j];
}
return copy;
}
旁注:
我还将k
放在for循环的范围内
您可能希望使用std::vector
或std::array
而不是使用原始数组
我发现您在定义函数int*reverse(int*,int);
reverse
函数的问题在于,您没有将指针传递给必须以相反顺序复制的源数组。相反,您传递了两个int
s
错误
错误->下标值不是数组、指针或向量
当您尝试使用size
作为数组时,通过向其添加下标size[j]
发生这种情况,因为size
是int
类型,而不是指针、数组或向量
我已将您的函数签名从
int* reverse(int elements, int size)
到
我修改了你的函数,使其看起来像这样
int* reverse(int *elements, int size)
{
int* copy = new int [size];
for(int j=size-1, k=0; j >=0; j--, k++)
{
// copy from elements and not size, elements is the array containing
// the values to be copied, size denotes the size of the array
copy[k] = elements[j];
}
return copy;
}
旁注:
我还将k
放在for循环的范围内
您可能希望使用std::vector
或std::array
而不是使用原始数组
我发现您在定义函数int*reverse(int*,int);
谢谢,现在很有意义。谢谢,现在很有意义。