如何更新传递给函数的数组

时间:2018-07-06 03:20:43

标签: c++ arrays pointers

我正在将数组int * foo = new int[n]传递到方法void bar(int * 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);
}

1 个答案:

答案 0 :(得分:-1)

下面是静态大小为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;
    }
}

更新栏内的值并在main中打印即可。