c - Dynamic memory allocation for 2D array -
I want to allocate memory to dynamically for 2D array.
Is there any difference between these two?
1)
array = (int **) malloc (size * size (int *)); For (i = 0; i
2)
array = (int **) malloc (size * size * sizeof (int));
If so, what's better and why?
In the first case
array = (int **) Malloc (Size * size (int *)); For (i = 0; i
You are allocating size to size
size of
In the second case expression
(int **) malloc (size * size * Sizeof (int))
That is, the allocation of a range of shapes * the size of objects of the type of size and the returned indicator is interpreted as int **
. So this expression has no meaning what is placed on the left side of the assignment. Keep in mind that the size of the pointer may be greater than the size of int.
You can write instead
int (* array) [size] = (int (*) [shape]) malloc (size * size * sized (int ));
In this case you are actually allocating a two-dimensional array, provided the size is a constant expression.
Comments
Post a Comment