Arrays 在C++;

Arrays 在C++;,arrays,pointers,memory,dynamic,allocation,Arrays,Pointers,Memory,Dynamic,Allocation,我正在编写一个程序,它应该查看指向整数的指针数组,然后让用户输入一个目标,然后程序应该用1替换找到的目标,用0替换其他值。我正在尝试动态分配指针数组,但由于某些原因,它不允许我这样做。我还无法从函数返回新数组(修改后),以便在main中打印它。我对指针还不是很在行,所以任何帮助都将不胜感激 谢谢大家! include<iostream> using namespace std; int* flagArray (int *p[], int n, int x) {

我正在编写一个程序,它应该查看指向整数的指针数组,然后让用户输入一个目标,然后程序应该用1替换找到的目标,用0替换其他值。我正在尝试动态分配指针数组,但由于某些原因,它不允许我这样做。我还无法从函数返回新数组(修改后),以便在main中打印它。我对指针还不是很在行,所以任何帮助都将不胜感激

谢谢大家!

include<iostream>
using namespace std;
int* flagArray (int *p[], int n, int x)     
{   
    for(int i = 0;i<n;i++)
    {
        if(x == *p[i])
        {
            *p[i] = 1;
        }
        else
            *p[i] = 0;
    }
    return *p; //Why wont this return the adresses of each of the 10 elements ? it only returns the adress of the first element.

}
void main()
{
    int const size = 10;
    int target;
    int *arr[] = new int*[size];    
    cout<<"fill the array : "<<endl;
    for(int i = 0;i<size;i++)
    {
        cin>>*arr[i];
    }
    cout<<"Enter the target : ";
    cin>>target;
    for(int j = 0;j<size;j++)
    {
    cout<<*(flagArray(arr,size,target))<<endl;  // works for first element only , rest are 0s since theyre not checked
    }
    delete []*arr;
}
包括
使用名称空间std;
int*flagArray(int*p[],int n,int x)
{   

对于(int i=0;这是错误的,在这么多的层次上……你可能不应该用动态数组来处理,因为你不知道你在做什么。好的旧代码<矢量< /代码>?”卡里姆:如果这是作业,你是否可以阻止使用C++标准库类,比如“代码>向量< /代码>?”他们可能会扣分数。@KarolyHorvath你能澄清为什么它在这么多级别上是错误的吗?在我将int*p更改为int*p[]作为函数的参数之前,以及在我将其从int arr[]更改为int*arr[]之前,它一直运行良好。我认为Karoly指的是存在不止一个问题的事实。例如,您创建了一个整数指针数组(创建有点可疑,令人惊讶的是它会按原样编译)。如果要创建数组,您仍然必须为数组中的每个元素创建(使用
new
)空间。因此,在
cin>*arr[I]
您应该执行
arr[i]=new int;
。您只需调用
flagArray
一次,然后在
arr[]
上循环。无需
flagArray
返回任何内容。您的数组由
flagArray
直接修改。然后在底部,您的
delete[]*arr
应该是
delete[]
。。。