C++ 如何更新传递到函数中的数组

C++ 如何更新传递到函数中的数组,c++,arrays,pointers,C++,Arrays,Pointers,我将一个排序为int*foo=new int[n]的数组传递给一个void barint*foo,int size方法。我的问题是,当我改变函数内的数组时,我可以打印它并查看更改,但是,在主要情况下,我单独调用另一个函数来打印foo,它似乎没有更新。有人能帮我吗 编辑:实际功能 注意:这是我正在进行的编码练习,因此我无法将数据结构更改为向量,也无法更改数组内存的存储方式。代码中唯一可以编辑的部分是heapRemove和heapPrint函数中的块 另一个编辑:我更改了将数组指针传递给方法的方式。

我将一个排序为int*foo=new int[n]的数组传递给一个void barint*foo,int size方法。我的问题是,当我改变函数内的数组时,我可以打印它并查看更改,但是,在主要情况下,我单独调用另一个函数来打印foo,它似乎没有更新。有人能帮我吗

编辑:实际功能

注意:这是我正在进行的编码练习,因此我无法将数据结构更改为向量,也无法更改数组内存的存储方式。代码中唯一可以编辑的部分是heapRemove和heapPrint函数中的块

另一个编辑:我更改了将数组指针传递给方法的方式。现在,它似乎更新了前两项,但没有更新其余的。你知道为什么吗?我更新了下面的代码

#include <iostream>
#include <string>
#include <sstream>
int readheap(int * theheap)
{
    //your code here
    //use std::cin to read in the data
    //return the size of the heap
    int value, count;
    while ( std::cin >> value) {
        theheap[count] = value;
        count++;
    }
    return count;
}

void heapRemove(int *& theheap, int& size)
{
   //your code here 
    theheap[0] = theheap[size - 1];
    int tempHeapArr[10];
    for (int i = 0; i < size - 1; i++) {
        tempHeapArr[i] = theheap[i];
    }
    theheap = tempHeapArr;
    size -= 1;

    int parent = 0;
    while (true) {
        int l = (2 * parent) + 1;
        int r = l + 1;
        int minChild = l;
        if (l >= size) {
            break;
        }
        if (r < size && theheap[r] < theheap[l]) {
            minChild = r;
        }
        if (theheap[parent] > theheap [minChild]) {
            int temp = theheap[parent];
            theheap[parent] = theheap[minChild];
            theheap[minChild] = temp;
            parent = minChild;
        }
        else
            break;
    }
        for ( int i = 0; i < size; i++) {
            std::cout << theheap[i] << " ";
        }
        std::cout << std::endl;
}

void heapPrint(int * theheap, int size)
{
    //use cout to print the array representing the heap
    for ( int i = 0; i < size; i++) {
            std::cout << theheap[i] << " ";
    }
}

int main()
{
    int * theheap = new int[10];
    int size = readheap(theheap);
    heapRemove(theheap, size);
    heapPrint(theheap, size);
}

下面是静态大小为5的代码

#include <string>
#include <iostream>
using namespace std;

void bar(int * foo, int size){
    foo[0] = 0;
    foo[1] = 1;
    foo[2] = 2;
    foo[3] = 3;
    foo[4] = 4;
}


int main(){
    int * foo = new int[5];
    bar(foo, 5);
    for(int i=0; i<5;i++){
       cout<<foo[i]<<endl;
    }
}

更新bar中的值并在main中打印,它就会工作。

显示您的代码。如果在main中看不到函数内部的更改,则bar的作用域很可能存在问题。你们确定酒吧里的变化不只是在酒吧结束时被破坏了吗?比如一个临时数组,或者某个地方缺少一个foo->?也很高兴看到条形码…我想看看条形码函数体以及你们是如何调用它的。请提供一个。此外,你可能不应该使用新的原始版本,如果你是出于传统原因学习的,那也没关系,但是如果你正在学习一门告诉你使用它的课程,那就放弃这门课程。对于数组的动态分配,我更喜欢std::vector。我试图让我的问题尽可能的笼统,但我知道我的问题并不完全清楚。我在编辑中发布了我的代码。这会起作用,但无法解决询问者遇到的问题。为了完全复制询问者的问题,bar必须将foo指向不同的数组。