0

Consider the following program:

void doSomething(char array[5])
{
    char b = 3;
    array[0] = b;
    return;
}

int main()
{
    char array[5] = {0, 1, 2, 3, 4};
    doSomething(array);
    return 0;
}

My question is, when passing the array to the doSomething function, is a copy of the array made and takes up more memory?, or is the pointer of the array simply passed, and the very same array is being modified?

  • 2
    Easy to check: print `array[0]` after the call! – Damien Oct 13 '20 at 14:56
  • the 2nd option is true – CIsForCookies Oct 13 '20 at 14:56
  • 1
    https://stackoverflow.com/questions/14309136/passing-arrays-to-function-in-c When you pass an array as an argument to a function, it decays to a pointer to the first element. – Nathan Pierson Oct 13 '20 at 14:56
  • 1
    Why don't you just test it? Check the array after calling the function. – Marco Bonelli Oct 13 '20 at 14:56
  • The parameter `char array[5]` is equivalent to `char* array`, and the call `doSomething(array)` is equivalent to `doSomething(&array[0])`. (This should be covered in any [decent book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).) – molbdnilo Oct 13 '20 at 14:57
  • Also you'd want to be more *specific* about whether you want to ask about C or C++ as they're two distinct and differing languages. – Antti Haapala -- Слава Україні Oct 13 '20 at 14:59
  • Since you tagged as C++ language, use `std::vector` not arrays. The `std::vector` can dynamically expand, can be queried for its size, and passed by reference to functions (with out having to pass an additional capacity parameter). – Thomas Matthews Oct 13 '20 at 16:32

0 Answers0