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 sizeof (int) that you are one-on-one Allocating shapes- dimensional arrays accordingly, you are allocating size signals which point to the first elements of these one-dimensional arrays.

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

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -