This question already has answers here:
Difference between pointer to pointer and pointer to array?
(3 answers)
Closed 5 years ago.
Can anyone please tell if both the entity - i.e.
2-D array char array[][9] and
array of pointers char *array[9] are same or different??
They are different.
The most prominent difference is that in the case of the array the elements will be laid out contigously in memory but in the case of the array of pointers they will not.
To be able to use the elements of the array of pointers, you need to make them point to some valid memory, you can do that either by using malloc() or by pointing to an array for example. In both cases the elements of the potential array the pointer points to are not contiguous.
Your confusion might be due to the fact that arrays can be syntactically used as pointers, because if you pass an array to a function expecting a pointer then, it is equivalent to a pointer that points to the first element of such array.
Also,
int x[3] = {1, 2, 3};
int *y = x;
is valid and you can use y as if it was an array even though it's not. It's a pointer, and you can use it to traverse the elements of the array x using pointer arithmetic.
One way of expressing such arithmetic is by the use of the [] syntax, in fact
int value = y[1]
is equivalent to performing a pointer arithmetic operation on y and dereferencing it, exactly equivalent to
int value = *(y + 1);
i.e. move to the element that is (1×sizeof *y) bytes after the beginning of y and get the value there.
Related
This question already has answers here:
Is an array name a pointer?
(8 answers)
Closed 5 years ago.
void main()
{
int array[10] = {1,2,3,4,5,6,7};
printf("%p\n",array);
}
Here, the system would allocate a memory in stack equivalent to 10 integers for the array. However, i dont think there is any extra memory allocate for the variable array, i presume array is a mnemonic for human understanding and coding purpose. If that is the case, how does the printf() in the statement - printf("%p\n",array); accept it as though it is a pointer variable?
This confusion becomes more evident as the dimension(s) of the array keeps increasing.
int main()
{
int matrix[2][4] = {{11,22,33,99},{44,55,66,110}};
printf("%p\n", matrix);
printf("%p\n", matrix+1);
printf("%p\n", *(matrix+1));
}
The ouput for one of the program execution was -
0x7ffd9ba44d10
0x7ffd9ba44d20
0x7ffd9ba44d20
So both matrix+1 and *(matrix+1), after indirection outputs the same virtual memory address. I understand why matrix+1 address is what it is displaying but i don't understand why *(matrix+1) is outputting the same address even after indirection!
Well arrays are not pointers. Most of the cases(the exceptions are sizeof,&operator, _alignof etc) - it is converted into (array decaying) pointer to first element.
So here matrix is converted (decay) into pointer to first element - which is int (*)[4] when passed to printf.
Now dissect one by one, matrix+1 will point to the second element of the 2d array which is the 2nd element of the 2d array (That's why they are sizeof(int)*4 times apart.
In the third case they are same, because matrix+1 is of type int (*)[4] and when you dereference it you get int[4] basically the same address as that of before.
There is one thing to keep in mind - with pointers there are two things
It's value
It's type.
Two pointers may have the same value but their type may be different. Here also you saw that.
It (decaying) is mentioned in standard 6.3.2.1p3:-
Except when it is the operand of the sizeof operator, the _Alignof 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.
Also you print the address in wrong manner (this is one of the case you would use casting).
printf("%p",(void*)matrix);
To make things a bit more clear:-
matrix is basically an object int[2][4] which decayed in the cases you have shown to int(*)[4]. You might wonder what is it that makes matrix+1
point to the second element of the array - the thing is pointer arithmetic is dicated by thing it points to. Here matrix as decayed into pointer to first element (int(*)[4]) it will move by an size of 4 ints.
I started learning C recently, and I'm having a problem understanding pointer syntax, for example when I write the following line:
int ** arr = NULL;
How can I know if:
arr is a pointer to a pointer of an integer
arr is a pointer to an array of pointers to integers
arr is a pointer to an array of pointers to arrays of integers
Isn't it all the same with int ** ?
Another question for the same problem:
If I have a function that receives char ** s as a parameter, I want to refer to it as a pointer to an array of strings, meaning a pointer to an array of pointers to an array of chars, but is it also a pointer to a pointer to a char?
Isn't it all the same with int **?
You've just discovered what may be considered a flaw in the type system. Every option you specified can be true. It's essentially derived from a flat view of a programs memory, where a single address can be used to reference various logical memory layouts.
The way C programmers have been dealing with this since C's inception, is by putting a convention in place. Such as demanding size parameter(s) for functions that accept such pointers, and documenting their assumptions about the memory layout. Or demanding that arrays be terminated with a special value, thus allowing "jagged" buffers of pointers to buffers.
I feel a certain amount of clarification is in order. As you'd see when consulting the other very good answers here, arrays are most definitely not pointers. They do however decay into ones in enough contexts to warrant a decades long error in teaching about them (but I digress).
What I originally wrote refers to code as follows:
void func(int **p_buff)
{
}
//...
int a = 0, *pa = &a;
func(&pa);
//...
int a[3][10];
int *a_pts[3] = { a[0], a[1], a[2] };
func(a_pts);
//...
int **a = malloc(10 * sizeof *a);
for(int i = 0; i < 10; ++i)
a[i] = malloc(i * sizeof *a[i]);
func(a);
Assume func and each code snippet is compiled in a separate translation unit. Each example (barring any typos by me) is valid C. The arrays will decay into a "pointer-to-a-pointer" when passed as arguments. How is the definition of func to know what exactly it was passed from the type of its parameter alone!? The answer is that it cannot. The static type of p_buff is int**, but it still allows func to indirectly access (parts of) objects with vastly different effective types.
The declaration int **arr says: "declare arr as a pointer to a pointer to an integer". It (if valid) points to a single pointer that points (if valid) to a single integer object. As it is possible to use pointer arithmetic with either level of indirection (i.e. *arr is the same as arr[0] and **arr is the same as arr[0][0]) , the object can be used for accessing any of the 3 from your question (that is, for second, access an array of pointers to integers, and for third, access an array of pointers to first elements of integer arrays), provided that the pointers point to the first elements of the arrays...
Yet, arr is still declared as a pointer to a single pointer to a single integer object. It is also possible to declare a pointer to an array of defined dimensions. Here a is declared as a pointer to 10-element array of pointers to arrays of 10 integers:
cdecl> declare a as pointer to array 10 of pointer to array 10 of int;
int (*(*a)[10])[10]
In practice array pointers are most used for passing in multidimensional arrays of constant dimensions into functions, and for passing in variable-length arrays. The syntax to declare a variable as a pointer to an array is seldom seen, as whenever they're passed into a function, it is somewhat easier to use parameters of type "array of undefined size" instead, so instead of declaring
void func(int (*a)[10]);
one could use
void func(int a[][10])
to pass in a a multidimensional array of arrays of 10 integers. Alternatively, a typedef can be used to lessen the headache.
How can I know if :
arr is a pointer to a pointer of an integer
It is always a pointer to pointer to integer.
arr is a pointer to an array of pointers to integers
arr is a pointer to an array of pointers to arrays of integers
It can never be that. A pointer to an array of pointers to integers would be declared like this:
int* (*arr)[n]
It sounds as if you have been tricked to use int** by poor teachers/books/tutorials. It is almost always incorrect practice, as explained here and here and (
with detailed explanation about array pointers) here.
EDIT
Finally got around to writing a detailed post explaining what arrays are, what look-up tables are, why the latter are bad and what you should use instead: Correctly allocating multi-dimensional arrays.
Having solely the declaration of the variable, you cannot distinguish the three cases. One can still discuss if one should not use something like int *x[10] to express an array of 10 pointers to ints or something else; but int **x can - due to pointer arithmetics, be used in the three different ways, each way assuming a different memory layout with the (good) chance to make the wrong assumption.
Consider the following example, where an int ** is used in three different ways, i.e. p2p2i_v1 as a pointer to a pointer to a (single) int, p2p2i_v2 as a pointer to an array of pointers to int, and p2p2i_v3 as a pointer to a pointer to an array of ints. Note that you cannot distinguish these three meanings solely by the type, which is int** for all three. But with different initialisations, accessing each of them in the wrong way yields something unpredictable, except accessing the very first elements:
int i1=1,i2=2,i3=3,i4=4;
int *p2i = &i1;
int **p2p2i_v1 = &p2i; // pointer to a pointer to a single int
int *arrayOfp2i[4] = { &i1, &i2, &i3, &i4 };
int **p2p2i_v2 = arrayOfp2i; // pointer to an array of pointers to int
int arrayOfI[4] = { 5,6,7,8 };
int *p2arrayOfi = arrayOfI;
int **p2p2i_v3 = &p2arrayOfi; // pointer to a pointer to an array of ints
// assuming a pointer to a pointer to a single int:
int derefi1_v1 = *p2p2i_v1[0]; // correct; yields 1
int derefi1_v2 = *p2p2i_v2[0]; // correct; yields 1
int derefi1_v3 = *p2p2i_v3[0]; // correct; yields 5
// assuming a pointer to an array of pointers to int's
int derefi1_v1_at1 = *p2p2i_v1[1]; // incorrect, yields ? or seg fault
int derefi1_v2_at1 = *p2p2i_v2[1]; // correct; yields 2
int derefi1_v3_at1 = *p2p2i_v3[1]; // incorrect, yields ? or seg fault
// assuming a pointer to an array of pointers to an array of int's
int derefarray_at1_v1 = (*p2p2i_v1)[1]; // incorrect; yields ? or seg fault;
int derefarray_at1_v2 = (*p2p2i_v2)[1]; // incorrect; yields ? or seg fault;
int derefarray_at1_v3 = (*p2p2i_v3)[1]; // correct; yields 6;
How can I know if :
arr is a pointer to a pointer of an integer
arr is a pointer to an array of pointers to integers
arr is a pointer to an array of pointers to arrays of integers
You cannot. It can be any of those. What it ends up being depends on how you allocate / use it.
So if you write code using these, document what you're doing with them, pass size parameters to the functions using them, and generally be sure about what you allocated before using it.
Pointers do not keep the information whether they point to a single object or an object that is an element of an array. Moreover for the pointer arithmetic single objects are considered like arrays consisting from one element.
Consider these declarations
int a;
int a1[1];
int a2[10];
int *p;
p = &a;
//...
p = a1;
//...
p = a2;
In this example the pointer p deals with addresses. It does not know whether the address it stores points to a single object like a or to the first element of the array a1 that has only one element or to the first element of the array a2 that has ten elements.
The type of
int ** arr;
only have one valid interpretation. It is:
arr is a pointer to a pointer to an integer
If you have no more information than the declaration above, that is all you can know about it, i.e. if arr is probably initialized, it points to another pointer, which - if probably initialized - points to an integer.
Assuming proper initialization, the only guaranteed valid way to use it is:
**arr = 42;
int a = **arr;
However, C allows you to use it in multiple ways.
• arr can be used as a pointer to a pointer to an integer (i.e. the basic case)
int a = **arr;
• arr can be used as a pointer to a pointer to an an array of integer
int a = (*arr)[4];
• arr can be used as a pointer to an array of pointers to integers
int a = *(arr[4]);
• arr can be used as a pointer to an array of pointers to arrays of integers
int a = arr[4][4];
In the last three cases it may look as if you have an array. However, the type is not an array. The type is always just a pointer to a pointer to an integer - the dereferencing is pointer arithmetic. It is nothing like a 2D array.
To know which is valid for the program at hand, you need to look at the code initializing arr.
Update
For the updated part of the question:
If you have:
void foo(char** x) { .... };
the only thing that you know for sure is that **x will give a char and *x will give you a char pointer (in both cases proper initialization of x is assumed).
If you want to use x in another way, e.g. x[2] to get the third char pointer, it requires that the caller has initialized x so that it points to a memory area that has at least 3 consecutive char pointers. This can be described as a contract for calling foo.
C syntax is logical. As an asterisk before the identifier in the declaration means pointer to the type of the variable, two asterisks mean pointer to a pointer to the type of the variable.
In this case arr is a pointer to a pointer to integer.
There are several usages of double pointers. For instance you could represent a matrix with a pointer to a vector of pointers. Each pointer in this vector points to the row of the matrix itself.
One can also create a two dimensional array using it,like this
int **arr=(int**)malloc(row*(sizeof(int*)));
for(i=0;i<row;i++) {
*(arr+i)=(int*)malloc(sizeof(int)*col); //You can use this also. Meaning of both is same. //
arr[i]=(int*)malloc(sizeof(int)*col); }
There is one trick when using pointers, read it from right hand side to the left hand side:
int** arr = NULL;
What do you get: arr, *, *, int, so array is a pointer to a pointer to an integer.
And int **arr; is the same as int** arr;.
int ** arr = NULL;
It's tell the compiler, arr is a double pointer of an integer and assigned NULL value.
There are already good answers here, but I want to mention my "goto" site for complicated declarations: http://cdecl.org/
Visit the site, paste your declaration and it will translate it to English.
For int ** arr;, it says declare arr as pointer to pointer to int.
The site also shows examples. Test yourself on them, then hover your cursor to see the answer.
(double (^)(int , long long ))foo
cast foo into block(int, long long) returning double
int (*(*foo)(void ))[3]
declare foo as pointer to function (void) returning pointer to array 3 of int
It will also translate English into C declarations, which is prety neat - if you get the description correct.
This question already has answers here:
Why can't we use double pointer to represent two dimensional arrays?
(6 answers)
Closed 6 years ago.
int main()
{
matrix[2][4] = {{11,22,33,99},{44,55,66,110}};
int **ptr = (int**)matrix;
printf("%d%d",**matrix,*ptr);
}
But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] ..
what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.
Is 2d array a double pointer?
No. This line of your program is incorrect:
int **ptr = (int**)matrix;
This answer deals with the same topic
If you want concrete image how multidimensional arrays are implemented:
The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:
matrix: 11 22 33 99 44 55 66 110
----------- the first element of matrix
------------ the second element of matrix
Therefore, to address element matrix[x][y], you take the base address of matrix + x*4 + y (4 is the inner array size).
When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]. The 4 in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y], you get matrix_ptr + x*4 + y, which is exactly the same as above.
The cast ptr=(int**)matrix is therefore incorrect. For once, *ptr would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1] anywhere in the memory of the program.
Note: the calculations in this post assume sizeof(int)==1, to avoid unnecessary complexity.
No. A multidimensional array is a single block of memory. The size of the block is the product of the dimensions multiplied by the size of the type of the elements, and indexing in each pair of brackets offsets into the array by the product of the dimensions for the remaining dimensions. So..
int arr[5][3][2];
is an array that holds 30 ints. arr[0][0][0] gives the first, arr[1][0][0] gives the seventh (offsets by 3 * 2). arr[0][1][0] gives the third (offsets by 2).
The pointers the array decays to will depend on the level; arr decays to a pointer to a 3x2 int array, arr[0] decays to a pointer to a 2 element int array, and arr[0][0] decays to a pointer to int.
However, you can also have an array of pointers, and treat it as a multidimensional array -- but it requires some extra setup, because you have to set each pointer to its array. Additionally, you lose the information about the sizes of the arrays within the array (sizeof would give the size of the pointer). On the other hand, you gain the ability to have differently sized sub-arrays and to change where the pointers point, which is useful if they need to be resized or rearranged. An array of pointers like this can be indexed like a multidimensional array, even though it's allocated and arranged differently and sizeof won't always behave the same way with it. A statically allocated example of this setup would be:
int *arr[3];
int aa[2] = { 10, 11 },
ab[2] = { 12, 13 },
ac[2] = { 14, 15 };
arr[0] = aa;
arr[1] = ab;
arr[2] = ac;
After the above, arr[1][0] is 12. But instead of giving the int found at 1 * 2 * sizeof(int) bytes past the start address of the array arr, it gives the int found at 0 * sizeof(int) bytes past the address pointed to by arr[1]. Also, sizeof(arr[0]) is equivalent to sizeof(int *) instead of sizeof(int) * 2.
In C, there's nothing special you need to know to understand multi-dimensional arrays. They work exactly the same way as if they were never specifically mentioned. All you need to know is that you can create an array of any type, including an array.
So when you see:
int matrix[2][4];
Just think, "matrix is an array of 2 things -- those things are arrays of 4 integers". All the normal rules for arrays apply. For example, matrix can easily decay into a pointer to its first member, just like any other array, which in this case is an array of four integers. (Which can, of course, itself decay.)
If you can use the stack for that data (small volume) then you usually define the matrix:
int matrix[X][Y]
When you want to allocate it in the heap (large volume), the you usually define a:
int** matrix = NULL;
and then allocate the two dimensions with malloc/calloc.
You can treat the 2d array as int** but that is not a good practice since it makes the code less readable. Other then that
**matrix == matrix[0][0] is true
This question already has answers here:
Is 2d array a double pointer? [duplicate]
(4 answers)
Closed 8 years ago.
What I learnt from C language is that
int **matrix = matrix is a pointer to pointer to int
when we want to create a matrix we will malloc a set of contigus pointers !
so here is the first pointer pointing to 1 pointer to an int or it can point to a set of pointers which are pointing to an int ( the first pointer will of course point to the address of the first pointer )
Brievely pointing to 1 pointer (only one ) is it the same as pointing to first pointer from a set of pointers ?
I think the answer resides inside this question What is exactly an array of something ?
Pointers and arrays are fundamentally different, especially wrt. to their behavior with sizeof() and wrt. what they allocate. However, they can sometimes be used interchangeably, because both essentially represent an address.
If you dynamically allocate memory, you will receive a pointer, which points to the beginning of a chunk of memory. If you allocate memory of a size that represents a multiple of a type's size, it should be intuitively clear that you can store as many elements of one type there, as you have allocated space for. Since C pointer arithmetic interprets *(p + n) - which is the same as p[n] and n[p] - as an access to the address of p plus n times the size of an element of the type p points to, it should now be easier to understand that you can interpret the pointer as the beginning of an array.
For your case, that means you can interpret int **p as a pointer to an int-pointer. Past the memory of this pointer, n more int pointers may follow, while every one of these pointers represents the address of an int, past which, once again, n more ints may follow. Thus, even though int **p is actually a pointer to a pointer of type int, it is possible to interpret it as two-dimensional array. How many elements past your pointer belong to the array is something that you cannot know from neither an array not a pointer, which is why you will usually have a n_size and/or m_size argument or something similar.
In the beginning I said that you can "sometimes" treat them as the same. To make this explicit, you can use pointers and arrays interchangeably in these cases:
When passed to a function a type[] "decays" to a type * e.g. f(type *a)
If accessing elements with the [] operator, a[i] always resolves to *(a + i)
When they occur in an expression, e.g. ++a
cf: van der Linden - Deep C
if you want a quick answer try making this tiny program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int matrix[2][3];
int **m;
m=malloc(sizeof(int *)*2);
m[0]=malloc(sizeof(int)*3);
m[1]=malloc(sizeof(int)*3);
m=matrix;
return 0;
}
The compiler will answer you that the two declarations are different. In fact:
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C: How come an array’s address is equal to its value?
SA
In C I tried to print the address of the pointer of an array.
int a[3] = {0,1,2};
printf("\n%p",a);
printf("\n%p",(&a));
the 2 statement prints the same value why?thanks in advance
Any array argument to a function will decay to a pointer to the first element of the array.
The C Book has an excellent explanation of this:
Another case is when an array name is
the operand of the & address-of
operator. Here, it is converted into
the address of the whole array. What's
the difference? Even if you think that
addresses would be in some way ‘the
same’, the critical difference is that
they have different types. For an
array of n elements of type T, then
the address of the first element has
type ‘pointer to T’; the address of
the whole array has type ‘pointer to
array of n elements of type T’;
clearly very different
In C arrays "decay" to pointers to their first element in certain contexts. Passing an array to a function is one of these cases.
Because local arrays are treated as a special case (they decay to pointers).
In your case &a is translated to a.
If you try with an int pointer, e.g.,
int c = 3;
int* p = &c;
you should get different values.
An array "decays" into a pointer to it's elements in some situations. Passing it as an argument to a function is one of those. Thus in
void func(int * pi, size_t nints);
int a[3] = {0, 1, 2};
func(a, 3);
the pointer to a is passed to func. This is what happens in your code as well. This also happens when you assign it to a pointer:
int * pi = a;
assert(*pi == 0); assert(*(pi + 1) == 1); assert(*(pi + 2) == 2);
The asserts here would also work if you replace pi with a.