what is the difference between these two pointer declaration - c

Here I have a 2D array. I want to declare a pointer to point to the first row of the array. First I did something like this
#include <stdio.h>
int main ()
{
int arr[2][2]={{6,2},{3,4}};
int *ptr=arr;
printf("%d",*(ptr+0));
}
First row of the 2D array is also a array. Similar type of pointer declaration for a 1D array don't give any warning. Why am I getting warning during compilation.
[Warning] initialization from incompatible pointer type [enabled by
default]
The following didn't give any warning
int main ()
{
int arr[2][2]={{6,2},{3,4}};
int (*ptr)[2]=arr;
printf("%d",*(ptr+0));
}

Except when it is the operand of the sizeof or unary & operators, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.
In the line
int *ptr=arr;
the expression arr has type "2-element array of 2-element array of int" (IOW, T is "2-element array of int"). Since the expression arr is not the operand of either the sizeof or unary & operators, it is converted ("decays") to an expression of type "pointer to 2-element array of int", or int (*)[2], and the value of the expression is the address of the first element of the array.
This is why you got the warning for the line above, but not for
int (*ptr)[2]=arr;
since in that case the types match correctly.
Given the declaration
int arr[2][2]={{6,2},{3,4}};
the following are all true:
Expression Type Decays To Equivalent Value
---------- ---- --------- ----------------
arr int [2][2] int (*)[2] &arr[0][0]
&arr int (*)[2][2] &arr[0][0]
*arr int [2] int * &arr[0][0]
arr[i] int [2] int * &arr[i][0]
&arr[i] int (*)[2] &arr[i][0]
*arr[i] int arr[i][0]
arr[i][j] int
&arr[i][j] int *
So arr, &arr, arr[0], &arr[0], and &arr[0][0] all evaluate to the same value (the address of the first element of an array is the same as the address of the array itself), but the types are all different.
A very important point I want to get across (especially because it's shown up in a couple of other answers) is that array objects do not store any pointer values. If you looked at the contents of arr in memory, you'd see something like the following:
+---+
arr: | 6 | arr[0][0]
+---+
| 2 | arr[0][1]
+---+
| 3 | arr[1][0]
+---+
| 4 | arr[1][1]
+---+
No storage is set aside anywhere for any pointers. When your code is compiled, any expressions that refer to arrays are replaced with pointers to the first element of the array.

arr is an array of arrays of integers while ptr is a pointer to an integer. In an array of arrays you need two levels of indirection to reach an integer (arr[0][0]) while in a pointer you need just one (ptr[0]). You can assign an array of elements of a certain type to a pointer to an element of the same type, but not if the types are different which is the case here.
As you can see, they are two different things so the compiler does a good job on whining on your assignation.

2D arrays contain (as arrurri mentioned) a pointer which points to an array of pointers and each of those point to the actual elements. So, arr is a pointer to pointers and each indexed value of it (arr[i]) is a pointer to a row.
So, what you need to do is ptr=arr[0]; instead.

Related

Creating a pointer to a 2D array

I am new to C and spend some hours with arrays and pointers.
Now, I got a specific question I can't really answer by myself.
What are the two variables mat_ptr and ptr which I create in this example and why are they different?
To me it looks like each is an array of pointers storing the pointers to the beginning of the 3 rows of the matrix.
int matrix[3][3] = {{0,1,2},
{0,1,2},
{0,1,2}};
int (*mtr_ptr)[3] = matrix;
int *ptr[3];
for (int i=0; i< 3; i++)
{
ptr[i]=matrix[i];
}
I the end, I think ptr ist of type int ** but what exactly is ptr_ptr?
A pointer to an array of size 3 which is an array of arrays?
This code:
int matrix[5][5] = {{0,1,2,3},
{0,1,2,3},
{0,1,2,3}}
is missing a semicolon at the end. When that is fixed, it defines matrix to be a 5×5 array (formally an array of 5 arrays of 5 int) in which rows 0 to 2 are initialized with four values (0, 1, 2, and 3), leaving element 4 implicitly initialized to zero. Rows 3 to 4 are implicitly initialized to zero.
This code:
int (*mtr_ptr)[3] = matrix;
defines mtr_ptr to be a pointer to an array of 3 int and attempts to initialize it with matrix. Since matrix is an array, it will be automatically converted to a pointer to its first element, matrix[0]. Thus, we have a pointer to an array of 5 int. This is not a proper type to initialize a pointer to an array of 3 int, so the compiler will complain.
If matrix were defined as int matrix[5][3] or int matrix[3][3], and the then-excess initializers were removed, then the types in int (*mtr_ptr)[3] = matrix; would match, and the compiler would not complain.
This code:
int *ptr[3];
for (int i=0; i< 3; i++)
{
ptr[i]=matrix[i];
}
defines an array of 3 pointers to int and assigns them values from matrix[i]. Since each matrix[i] is an array, it will be converted to a pointer to its first element, matrix[i][0]. So each ptr[i] will be assigned to point to matrix[i][0].
First things first. There is a semi-colon missing from the definition of matrix, corrected below:
int matrix[5][5] = {{0,1,2,3},
{0,1,2,3},
{0,1,2,3}};
Regarding the definition of mtr_ptr below:
int (*mtr_ptr)[3] = matrix;
mtr_ptr is declared as a pointer to an array length 3 of ints. However, it is being initialized with an incompatible pointer. matrix is an array length 5 of array length 5 of int. In the assignment expression above, matrix is converted to a pointer to the first element. The elements of matrix have type array length 5 of int, so matrix is converted to a pointer to array length 5 of int with value equivalent to &matrix[0]. Therefore, mtr_ptr should be defined as:
int (*mtr_ptr)[5] = matrix;
or equivalently:
int (*mtr_ptr)[5] = &matrix[0];
Regarding the code below:
int *ptr[3];
for (int i=0; i< 3; i++)
{
ptr[i]=matrix[i];
}
ptr is defined as an array length 3 of pointers to int. matrix[i] is an array length 5 of int. In the assignment expression, it is converted to a pointer to its first element. The element type is int, so matrix[i] is converted to a pointer to int equivalent to &matrix[i][0]. Therefore, the assignement ptr[i]=matrix[i]; is equivalent to ptr[i]=&matrix[i][0];.
These declarations
int matrix[5][5] = {{0,1,2,3},
{0,1,2,3},
{0,1,2,3}}
int (*mtr_ptr)[3] = matrix;
do not make a sense. It seems you mean at least the following declarations
int matrix[3][4] = {{0,1,2,3},
{0,1,2,3},
{0,1,2,3}};
int (*mtr_ptr)[4] = matrix;
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array
object has register storage class, the behavior is undefined.
So the array matrix used in expressions with rare exceptions is converted to pointer to its initial element of the type int ( * )[4].
Thus in this declaration
int (*mtr_ptr)[4] = matrix;
the pointer mtr_ptr is initialized by the address of the first "row" of the array matrix.
On the other hand, the expression matrix[i] is the i-th element of the array matrix that has the type int[4]. Such an array used in expression is in turn converted to pointer to its first element of the type int *.
In this line
int *ptr[3];
there is declared an array of three elements of the type int *.
And in this loop
for (int i=0; i< 3; i++)
{
ptr[i]=;
}
each element of the array of pointers is assigned by the address of the first element of the corresponding "row" of the array matrix that ("row") used in the expression matrix[i] is implicitly converted to pointer.
Unless it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.
In the line
int (*mtr_ptr)[3] = matrix;
the expression matrix has type "5-element array of 5-element array of int". Since matrix is not the operand of the sizeof or unary & operators, it "decays" to type "pointer to 5-element array of int", or int (*)[5], and its value is the address of the first element of matrix (same as &matrix[0]).
int (*)[5] and int (*)[3] are different, incompatible types, so the compiler should yak at you on that initializer. You should declare mtr_ptr as
int (*mtr_ptr)[5] = matrix;
Remember that mtr_ptr is a pointer, not an array - it stores a single value.
That single value has type int (*)[5].
By contrast, the expression matrix[i] has type "5-element array of int"; by the same rule above, that expression "decays" to type "pointer to int", or int *. Since each element of your ptr array is storing an int *, you declare it as
int *ptr[3];
In this case ptr is an array, and each element simply stores an int *. That pointer may be the address of the first element matrix[i], or it may be a pointer to a single int object that isn't part of a larger array, or it may be something else:
ptr[0] = matrix[0];
ptr[1] = &i;
...
The size of ptr does not depend on the size of matrix beyond whether or not you want to store the address of all rows or matrix or just a subset.

Why pointer of type int (*ptr)[10] requires address of the array and not just array itself

Array returns pointer to the first element. I have simple code as below:
int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = a;
I am getting below warning.
warning: assignment from incompatible pointer type
If i modify the pointer definition as shown below then there is no warning
ptr = &a;
Why does the first assignment results in warning? Does &a returns integer pointer to array of 10 elements? Pls help to understand. Thanks
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
Except for the sizeof, & and alignof operator, arrays decay to pointers.
int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = a;
In the assignment ptr = a, a decays to a pointer to int (int *), which points to the first element.
int a[10] = {1,2,3};//Filled three elements
int (*ptr)[10];//pointer to an array of 10 ints
ptr = &a;
Here &a is of type int (*)[10], which is a pointer to an array of 10 ints and has the same type as ptr. It is the proper way to assign a pointer to an array.
Also note that the value itself is the same for a and &a, the only difference is the type.

the address for the array pointer, &array [duplicate]

This question already has answers here:
How come an array's address is equal to its value in C?
(6 answers)
Closed 7 years ago.
The following program prints that a and array share the same address.
How should I understand this behavior?
Is it &arr the address for the pointer arr, which contains the beginning address the 10 chars?
#include <stdio.h>
int main()
{
char arr[10] = {0};
char* a = (char*)(&arr);
*a = 1;
printf("a=%p,arr=%p.\n", a, arr);
printf("%d\n", arr[0]);
return 0;
}
When you allocate an array in C, what you get is something like the following:
+---+
arr[0]: | |
+---+
arr[1]: | |
+---+
...
+---+
arr[N-1]: | |
+---+
That's it. There's no separate memory location set aside for an object named arr to store the address of the first element of the array. Thus, the address of the first element of the array (&arr[0]) is the same value as the address of the array itself (&arr).
Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.
So the type of the expression arr in the first printf call is char [10]; by the rule above, the expression "decays" to type char *, and the value is the address of arr[0].
In the expression &arr, arr is the operand of the unary & operator, so the conversion isn't applied; instead of getting an expression of type char **, you get an expression of type char (*)[10] (pointer to 10-element array of char). Again, since the address of the first element of the array is the same as the address of whole array, the expressions arr and &arr have the same value.
In idiomatic C, you should write char *a = arr; or char *a = &(arr[0]);. &arr is normally a char **. Even if modern (C++) compilers fixe it automatically, it is not correct C.
As arr is an array of char, arr[0] is a char and arr is the same as &(arr[0]) so it is a char *. It may be strange if you are used to other languages, but it is how C works. And it would be the same if arr was an array of any other type including struct.
The address printed out by arr and a is the memory address of the first element of the array arr. (Remember, the name of an array is always a pointer to the first element of that array.) This is because after you have defined the array arr, you define a as a pointer to the same address in memory.
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array object
has register storage class, the behavior is undefined.
The address of an array is the address of its first element. So though these types are different
char ( * )[10] ( that corresponds to &arr ) and char *(that is used in the casting in statement
char* a = (char*)(&arr); ) they will have the same value that is the address of the first element of the array.
If you would not use the casting then the correct definition of the pointer initialized by expression &arr would be
char ( *a )[10] = &arr;
The difference is seen then the pointer is incremented. For your definition of pointer a the value of expression ++a will be greater sizeof( char) than the initial value . For the pointer I showed the value of expression ++a will be greater 10 * sizeof( char ) than the initial value.
In your case the type of expression *a is char and you may write *a = 1; while in my case the type of expression *a will be char[10] and you may not write *a = 1;

how to give base address of 2d array to pointers

Suppose we have
int a[2][3] ;
int (*p)[3]=a; // is ok
int (*p)[3]=&a[0]; // is also ok
but why is
int (*p)[3]=a[0];
producing errors , although a[0] gives first array's address(as 2d arrays are array of array) and seems more
okay than &a[0] which gives address of first element of first array still is ok but why?
Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.
Given the declaration
int a[2][3];
Then the following are true:
Expression Type Decays To Equivalent Value
---------- ---- --------- ----------------
a int [2][3] int (*)[3] &a[0]
&a int (*)[2][3] n/a n/a
*a int [3] int * a[0]
a[i] int [3] int * n/a
&a[i] int (*)[3] n/a n/a
*a[i] int n/a a[i][0]
a[i][j] int n/a n/a
Note that a, &a, *a, a[0], &a[0], and &a[0][0] all yield the same value (the address of the first element of the array is the same as the address of the array), but the types are different.
As you can see from the table above, the expression a[0] has type "3-element array of int"; since that expression is not the operand of the sizeof or unary & operators, it is converted to an expression of type "pointer to int", which is not compatible with "pointer to 3-element array of int", which is why int (*p)[3] = a[0]; throws an error.
Because a[0] is not a pointer type, but an int[3] type. A block of 3 integers which can be assigned to such, but not to a pointer.
int (*p)[3]=a; // is OK
because a is of type int (*)[3] (pointer to an array of 3 ints), after decay to the first element which is also the type of p. Assignment is legal.
int (*p)[3]=&a[0]; // is also OK
because &a[0] is also of type int (*)[3] (address of the first row)
int (*p)[3]=a[0]; // is not OK
because a[0] is of type int * after decay to the first element of row 0. Assignment of different pointer types is illegal.
How a[0] can be of type int or int[3] as we have declared it a 2d array

Pointers to arrays problem in C

I have this function that takes a pointer of an array (in order to modify it from within the function)
int func_test(char *arr[]){
return 0;
}
int main(){
char var[3];
func_test(&var);
return 0;
}
When I try to compile this I get :
passing argument 1 of ‘func_test’ from incompatible pointer type
Why is this problem, and how I pass a pointer to that array in this case?
char * arr[] is not a pointer to an array; it is an array of pointers. Declarations in C are read first from the identifier towards the right, then from the identifier towards the left. So:
char * arr[];
// ^ arr is...
// ^ an array of...
// ^ pointers to...
// ^ char
A pointer to an array is a type (*varname)[], in your case, a char (*arr)[].
You are passing the address of a pointer. I think you want this:
int func_test(char arr[]){
arr[0] = 'a';//etc.
return 0;
}
int main(){
char var[3];
func_test(var);
return 0;
}
char var[3] is an array that holds 3 characters, not 3 pointers to characters - char *arr[] denotes an array that holds pointers to characters.
So you can go like this:
char *var[3];
func_test(var);
Note that the ampersand is not needed because array identifiers automatically decay to pointers of the corresponding type, in this case char **.
That's because the name of an array is already a pointer to it, so use func_test(var).
&var will have type char**
This is an array of pointers
char *arr[]
This is an address of a pointer
&var
So you are passing something different to what the function expects
C's treatment of arrays is a little confusing at first.
Except when it's an operand of either the sizeof or unary & operators, or when it's a string literal being used to initialize another array in a declaration, an expression with type "N-element array of T" will be implicitly converted to type "pointer to T", and its value will be the address of the first element in the array.
Assume the following declaration:
int x[10];
The type of the expression x is "10-element array of int". However, when that expression appears as, say, a parameter to a function:
foo(x);
the type of x is implicitly converted ("decays") to type "pointer to int". Thus, the declaration of foo needs to be
void foo(int *p);
foo receives an int *, not an int [10].
Note that this conversion also occurs for something like
i = x[0];
Again, since x isn't an operand of sizeof or &, its type is converted from "10-element array of int" to "pointer to int". This works because array subscripting is defined in terms of pointer arithmetic; the expression a[n] is equivalent to *(a+n).
So for your code, you'd write
int func_test(char *arr) { return (0); }
int main(void)
{
char var[3];
func_test(var); // no & operator
return 0;
}
Postfix operators like [] have higher precedence than unary operators like *, so a declaration like T *a[N] is interpreted as T *(a[N]), which declares an array of pointer to T. To declare a pointer to an array, you have to use parentheses to explicitly group the * operator with the array name, like T (*a)[N].
Here's a handy table of array declarations, expressions, and types:
Declaration: T a[N]; // a is an N-element array of T
Expression Type Decays To
---------- ---- ---------
a T [N] T *
&a T (*)[N]
a[i] T
&a[i] T *
Declaration: T *a[N]; // a is an N-element array of pointer to T
Expression Type Decays To
---------- ---- ---------
a T *[N] T **
&a T *(*)[N]
a[i] T *
*a[i] T
&a[i] T *
Declaration: T (*a)[N] // a is a pointer to an N-element array of T
Expression Type Decays To
---------- ---- ---------
a T (*)[N]
&a T (**)[N]
*a T [N] T *
(*a)[i] T

Resources