What is the difference between these two declarations "int ** matrix" and "int matrix [] []"?

What I learned in C is that int ** matrix = matrix is ​​a pointer to a pointer to an int when we want to create a matrix we will malloc a set of adjacency pointers! so here is the first pointer pointing to 1 pointer to int or it can point to a set of pointers that point to int (the first pointer will of course point to the address of the first pointer)

Brievely points to 1 pointer (only one), is this the same as pointing to the first pointer from a set of pointers?

I think the answer is inside this question. What is an Array?

+3


source to share


2 answers


Pointers and arrays are fundamentally different, especially wrt. to their behavior with sizeof()

and wrt. what they emit. However, they can sometimes be used interchangeably because both are essentially an address.

If you allocate memory dynamically, you get a pointer that points to the beginning of the chunk of memory. If you are allocating memory of a size that is a multiple of the size of a type, it should be intuitive that you can store as many elements of the same type as you have been allocated. Since the C-pointer arithmetic interprets *(p + n)

- the same as that of p[n]

, and n[p]

- as an access to the address p

plus n

times the size of the element type p

indicates, it should now be easier to understand that you can be interpreted as a pointer to the beginning of the array.

In your case, this means that you can interpret it int **p

as a pointer to int

-pointer. Remember this pointer, n

further pointers int

may follow, while each of these pointers represents an address int

past which, once again, n

may follow ints

. Thus, although int **p

it is actually a pointer to a type pointer int

, it can be interpreted as a two-dimensional array. How many elements your pointer owns in an array is something you cannot know from either the array or the pointer, so you usually have an argument n_size

and / or m_size

or something similar.



I said in the beginning that you can "sometimes" treat them as one. To make it explicit, you can use pointers and arrays in these cases:

  • When passed to a function, a type[]

    "splits" into type *

    eg.f(type *a)

  • If accessing elements with operator []

    , a[i]

    always allows*(a + i)

  • When they occur in an expression, for example. ++a

cf: van der Linden - Deep C

+6


source


if you want a quick answer try 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 tell you that the two declarations are different. In fact: warining

+1


source







All Articles