samedi 1 février 2020

How come we can initialize Array using PassByValue but we can't change Array Content through PassByValue?

So i have short program in C++ in which im taking input from user in an array in this function void Arr(int inputArr[]) later i am trying to increment individual values of elements of same array in this functionvoid IncrementArrayElement(int Arr[]) and it doesn't change values of original array elements.

What i don't understand is how can we Initialize array through pass by value but in order to perform operations on actual i need refrence.

#define Log(x) std::cout <<x <<std::endl
static const int arrLength = 4;

//taking input through pass by value
void Arr(int inputArr[]) {
    for (int i = 0; i < arrLength; i++) {
        Log("enter elements");
        std::string s;
        std::getline(std::cin, s);
        int a = std::atoi(s.c_str());
        inputArr[i] = a;
    }
}
//incrementing value of array i through pass by value
void IncrementArrayElement(int Arr[]) {
    for (int i = 0; i < arrLength; i++) {
        Arr[i] = Arr[i]++;
    }
}

int main() {
    int inputArr[arrLength];
    Arr(inputArr);
IncrementArrayElement(inputArr);
    for ( int i = 0; i <arrLength; i++) {
        Log(inputArr[i]);
    }
    std::cin.get();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire