bintom said:
Is there any difference between the following function prototypes?
void func(int arr [ ]);
and
void func(int *ptr);
When I print the address of arr and ptr, they reflect the same value
(address of the array). I can even say arr++ and ptr++ without any
problem.
So, is there any difference between the two?
It's amazing how, after some passage of time and experience, it is
sometimes necessary to have to think anew about the more basic stuff
learnt a long time ago. I'd initially merely wanted to say no
difference, but then had to think about it from various angle and test a
few things. The key here is the array-to-pointer conversion.
19:08:23 Paul Bibbings@JIJOU
/cygdrive/d/CPPProjects/CLCPP $cat array_ptr_comp.cpp
// file: array_ptr_comp.cpp
#include <iostream>
void f(int arr[])
{
std::cout << "\nsizeof(arr): " << sizeof(arr) << '\n';
std::cout << "&arr : " << arr << '\n';
std::cout << "*arr++ : " << *arr++ << '\n';
std::cout << "*arr : " << *arr << '\n';
}
void g(int *ptr)
{
std::cout << "\nsizeof(ptr): " << sizeof(ptr) << '\n';
std::cout << "&ptr : " << ptr << '\n';
std::cout << "*ptr++ : " << *ptr++ << '\n';
std::cout << "*ptr : " << *ptr << '\n';
}
int main()
{
int i_arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
void (*f_ptr)(int []) = 0;
void (*g_ptr)(int *) = 0;
f_ptr = &g;
g_ptr = &f;
f_ptr(i_arr);
g_ptr(i_arr);
}
You can see that the array-to-pointer conversion is applied even when
generating the function signature (compiled with gcc-4.4.3):
/cygdrive/d/CPPProjects/CLCPP $nm --demangle --defined-only
array_ptr_comp.o
// ...
00000000 T f(int*)
000000e2 T g(int*)
Regards
Paul Bibbings