Search code examples
c++arrayspointersstackdynamic-arrays

After passing by reference to modify an array, why it stays the same?


I am practicing pointers by creating a Big Number struct, which has numDigits (number of digits) and digits (contents of the big number).

I create a function called removeZero(). After passing the integer array and the size n into it, because of passing by reference, I am supposed to cut down the leading zeros for my input. It works, when the integer array is in main function. However, when I pass an array that is in readDigits, it does not return with a non-leading-zero version. Why? How to fix it?

struct BigNum{
    int numDigits;
    int *digits;  //the content of the big num
};

int main(){
    int A[] = {0,0,0,0,0,0,1,2,3};
    int n=9;
    int *B=A;
    //removeZero(A,n); If I use this, it cannot compile
    //error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’

    removeZero(B,n);
    for (int i=0; i<n; i++){
    std::cout << *(B+i) << std::endl;
    }

    BigNum *num = readDigits();

    return 0;
}

BigNum* readDigits(){  
    std::string digits;
    std::cout << "Input a big number:" << std::endl;
    std::cin >> digits; 

    //resultPt in heap or in stack?
    int *resultPt = new int[digits.length()]; //in heap
    int n = digits.length();
    toInt(digits,resultPt);
    removeZero(resultPt,n);

    //Output the leading zeros, why?
    for (int i=0; i<n; i++){
    std::cout << *(resultPt +i) << std::endl;
    }

    BigNum *numPtr = new BigNum();
    numPtr->numDigits = n;
    numPtr->digits = resultPt;

    return numPtr;
}

void toInt(std::string& str, int *result){
    for (int i=0;i<str.length() ;i++ ){
    result[str.length()-i-1] = (int)(str[i]-'0');
    }
}

void removeZero(int* &A,int& n){
    int i=0;
    while (A[i]==0){
    i++;
    }
    A=A+i; //memory leak?
    n=n-i;
}

bool areDigits(std::string num){
    for(int i=0;i<num.length();i++){
    if(num[i]<'0' || num[i] >'9'){
        return false;
     }
    }
    return true;
}

Solution

  • Note that an array and a pointer are two different things. When you pass an array to a function, it degrades to a const pointer. This means that you cannot pass an array to a function which expects a int*&.