I know that arrays are similar to pointers in C. Is it safe to say that this means that when I pass an array, say int array[3] = {1, 2, 3}, to another method that changing the values of the passed-in array to int array[3] = {3, 2, 1} change the original array as well? If so, does that mean I essentially don't have to return arrays I pass in due to the fact that any value changes I make to the passed-in array changes the original array's values? (as I understand it, it is in fact impossible to have a function return arrays directly.)
-
1Yes, passing an array is just passing its address.user4098326– user40983262015-02-18 06:33:32 +00:00Commented Feb 18, 2015 at 6:33
-
3No, arrays are not just pointers. Why people keep repeating this factually incorrect statement?n. m. could be an AI– n. m. could be an AI2015-02-18 06:38:00 +00:00Commented Feb 18, 2015 at 6:38
-
possible duplicate of what is array decaying?n. m. could be an AI– n. m. could be an AI2015-02-18 06:40:26 +00:00Commented Feb 18, 2015 at 6:40
-
1Arrays are not even almost the same as pointers. And arrays cannot be passed as arguments to functions. Read section 6 of the comp.lang.c FAQ.Keith Thompson– Keith Thompson2015-02-18 06:50:35 +00:00Commented Feb 18, 2015 at 6:50
-
You can't pass an array to a function, so the question is moot.Stack Exchange Broke The Law– Stack Exchange Broke The Law2015-02-18 07:04:21 +00:00Commented Feb 18, 2015 at 7:04
2 Answers
You cannot pass an array to a function that way. When you write this:
void myFunc(int ar[]) {
// ar *looks like* an array?
}
int main() {
int array[3] = {1,2,3};
myFunc(array);
}
the compiler will translate it to this:
void myFunc(int *ar) {
// nope, it's actually a pointer...
}
int main() {
int array[3] = {1,2,3};
myFunc(&array[0]); // ... to the first element
}
I recommend not using the void myFunc(int ar[]) syntax, since it only causes confusion. (Writing array instead of &array[0] is acceptable, but only because it's shorter.)
As for your question: since you're actually passing a pointer to the array, then yes, modifying the array the pointer points to will modify the original array (because they're the same array).
Comments
int array[3] = {1,2,3};
myFunc(array);// you are actually passing the base address of the array to myFunc.
your function declaration of myFunc()
void myFunc(int arr[])
{
}
But it is always good to pass the size of the array to the function along with the base address of array,this will help in avoiding array bound errors.
4 Comments
int arr[] is adjusted to int *arr. So all you have in such a function is a pointer. All array size information is lost.void foo(const int (*arr)[10]), then sizeof(*arr) gives the size of the array. But in that case you know its length anyway so there isn't much gain. And C compilers will mostly let you make the mistake of passing an array of the wrong size.