In C, array name represents address and when we pass an array, we actually pass address and the parameter receiving function always accepts them as pointers (even if we use , refer this for details).
How to pass array by value, i.e., how to make sure that we have a new copy of array when we pass it to function?
This can be done by wrapping the array in a structure and creating a variable of type of that structure and assigning values to that array. After that, passing the variable to some other function and modifying it as per requirements. Note that array members are copied when passed as parameter, but dynamic arrays are not. So this solution works only for non-dynamic arrays (created without new or malloc).
Let’s see an example to demonstrate the above fact using a C program:
In 'modify()', before modification 10 10 10 10 10 In 'modify()', after modification 100 100 100 100 100 In 'Main', after calling modify() 10 10 10 10 10
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- strpbrk() in C
- ispunct() function in C
- strcpy in C/C++
- Pointer to an Array | Array Pointer
- strdup() and strndup() functions in C/C++
- strtok() and strtok_r() functions in C with examples
- Programs for printing pyramid patterns in C++
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Creating a Rainbow using Graphics Programming in C
- Passing by pointer Vs Passing by Reference in C++
- Different methods to reverse a string in C/C++
- How to pass a 2D array as a parameter in C?
- Are array members deeply copied?
- Do not use sizeof for array parameters
- Why C treats array parameters as pointers?