Hi I am trying to understand the difference between passing a 2d array of type char
VS type int
to a function as a double-pointer func(int **ptr)
parameter. The problem is that it behaves differently. Below I will show two examples for type char
and int
using PythonTutor for C.
I looked at the whole internet and asked some friends but couldn't find an answer to the behavior.
Example with type char: int func(char **arr)
{
printf("%d", **arr);
}
int main()
{
char *arr[] = {"char1","char2"};
return 0;
}
Example with type int:
int func(int **arr)
{
printf("%d", **arr);
}
int main()
{
int *arr[] = {{1,3},{4,5,6}};
return 0;
}
One thing to note is that is not important what the func body is doing with the double-pointer passed to it, the problem i am trying to understand is why the double-pointer in the case of 2D char array is pointing to a pointer to integer while the 2D int array is not pointing to the integers within the arrays?
Below is the visualization from pythontutor for both cases.
Example with type char 2D array: http://pythontutor.com/c.html#mode=display
Example with type int 2D array: http://pythontutor.com/c.html#mode=display
Also provide snapshot of the final result:
Example with type char 2D array:
Example with type int 2D array:
int *arr[]
is not a 2D array, it is an array-of-pointers-to-int.int arr[x][y]
withx & y
are integer literals creates a 2D array. (which on access will be converted to a pointer to the first element (which is a pointer the first 1D array, e.g. a pointer to array of int[y]) which is not the same asint**
(which is simply a pointer to pointer to int).type *arr[]
is an array of pointers. What follows, e.g.char *arr[] = {"one", "two"};
must be pointers. Forint *arr[];
you would need for instanceint a[] = {1, 2, 3);
andint b[] = {3, 4, 5};
, thenint *arr[] = {a, b};
as botha
andb
will be converted to pointers on access. C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3). Also a 2D array is actually an array of 1D arrays. You can represent asint arr[x][y];
orint (*arr)[y];
Sotype (*arr)[y];
is a pointer to array.