c++ - 输出逻辑错误

标签 c++ arrays pointers allocation

我正在开发一个使用指针创建动态数组然后重新分配它的程序。

问题是程序运行成功但输出错误。任何帮助,将不胜感激。

int main()
{
    int n;
    cout<<"Please enter the size of the array: ";
    cin>>n;

    int *arr1;
    arr1 = new int[n];
    int *arr1_1;

    arr1_1=arr1;

    cout<<"Enter "<<n<<" elements in the array \n";
    int x=0;

    while(x<n)
    {
        cin>>arr1[0];
        arr1++;
        x++;
    }

    x=0;
    arr1=arr1_1;

    cout<<"Here's what you've inserted in the array: \n";
    while(x<n)
    {
        cout<<arr1[0]<<endl;;
        arr1++;
        x++;
    }

    arr1=arr1_1;

    cout<<"\n\n";
    cout<<"Do you want to extend the size of the array? \nAnswer with 'Y' or 'N'. "<<endl;
    char ans;
    cin>>ans;

    int n1;
    if(ans=='Y' || ans=='y'){
        cout<<"According to you, What should be the new size of array? ";
        cin>>n1;
        cout<<"You can enter new elements in your existing array now.\n"; 
    }
    else{
        cout<<"Ok, then! Have a nice day.";
    }

    int *arr2, *arr2_1;

    arr2=(int *) realloc (arr1, n1*sizeof(int));

    arr2_1=arr2;
    x=0;

    while(x<n)
    {
        arr2[0]=arr1[0];
        arr1++;
        arr2++;
        x++;
    } 

    x=n;
    while(x<n1){
        cin>>arr2[n+1];
        arr2++;
        x++;
    }
    arr2=arr2_1;
    x=0;


    while(x<n1){
        cout<<arr2[0]<<endl;
        arr2++;
        x++;
    }

    return 0;
}

最佳答案

有两个主要问题:第一个问题是您使用两个不同的系统进行内存分配。 newrealloc 都返回指针,但是 newrealloc 不是同一系统的一部分,不应该混合。您要么使用 C++,要么使用 C,不要混用。

第二个问题是,当你第二次读入数据时,你没有将arr2重置为指向上面复制循环中分配的数据的开始,所以你写越界。

此外,如果您决定采用 C 方式并使用 mallocreallocfree,您应该知道 realloc 正是这样做的,它重新分配现有内存,包括复制数据,因此您不必进行手动复制。此外,为什么要首先使用 relloc(和复制),而您要做的第一件事就是覆盖所有数据?


作为旁注,我认为您了解指针及其工作原理是件好事,但将来当您想要使用“动态数组”时,您应该使用 std::vector 来实现。 .

关于c++ - 输出逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352331/

相关文章:

c++ - 在 Linux 32 位上带有基数 36 的 strtoull 溢出 unsigned long long

c++ - 为什么我们没有义务实现纯虚析构函数?

Java 内存不足数组错误

c - 返回一个字符指针数组

c++ - 变量、指针、对象和内存地址 : Why do I get this strange result?

c - 如何通过引用传递动态分配的二维数组中的子数组?

c++ - 通过带有Visual Studio 2015的NuGet包的OpenCV,如何配置?

C++指针问题

java - 穿过迷宫时出现堆栈溢出错误

python - 使用另一个数组和索引数组创建 numpy 数组