为什么数组最后打印不同的元素?

时间:2021-02-13 20:55:41

标签: c++ arrays

#include <iostream>
using namespace std;
int *position(int N,int vet2[], int x, int pos){
    N++;
    for(int i = N;i>=pos;i--){
        vet2[i]=vet2[i-1];
    }
    vet2[pos-1]= x;
    return vet2;
}
int main(int argc, const char * argv[]) {
    int N;
    cout<<"insert the dimention of the array"<<endl;
    do{
        cin>>N;
    }while((N%2)!=0);
    int vet[N],vet2[N];
    cout<<"insert the elements of the array"<<endl;
    for(int i = 0;i<N;i++){
        cin>>vet[i];
    }
    cout<<"the elements of the array n°1 are:"<<endl;
    for(int i = 0;i<N;i++){
        cout<<vet[i]<<" ";
    }
    cout<<endl;
    for(int i = 0;i<N;i++){
        vet2[i]=vet[i];
    }
    int x = 0;
    int pos = 2;
    for(int i = 0;i<N;i++){
        position(N, vet2, x, pos);
        pos += 2;
    }
    cout<<"the elements of array n°2 are:"<<endl;
    for (int i = 0;i<2*N;i++){
        cout<<vet2[i]<<" ";
    }
    return 0;
}

例子:数组的输入是1 2 3 4 5 6,vet2的输出必须是1 0 2 0 3 0 4 0 5 0 6 0但是程序编译时vet2的输出是1 0 2 0 3 0 4 0 1 0 3 0

为什么会这样,我真的不知道为什么数组打印不同的元素?

1 个答案:

答案 0 :(得分:0)

您创建了一个大小为 vet2 的数组 N

int vet[N],vet2[N];

但是您的程序假定它的大小为 2*N

for (int i = 0;i<2*N;i++){
    cout<<vet2[i]<<" ";

改变

int vet[N],vet2[N];

int vet[N],vet2[2*N];

编辑

position 函数被窃听。不用了,改一下代码

for(int i = 0;i<N;i++){
    vet2[i]=vet[i];
}
int x = 0;
int pos = 2;
for(int i = 0;i<N;i++){
    position(N, vet2, x, pos);
    pos += 2;
}

更简单的

for (int i = 0; i < N; i++) {
    vet2[2*i] = vec[i];
    vet2[2*i + 1] = 0;
}
相关问题