user12239061
user12239061

Reputation:

Use of pointers in dynamic memory allocation

Can someone explain to me why when I dynamic allocate memory with calloc or malloc I declare:

int *arr
int n
arr = malloc(n * sizeof(int))

and not

*arr = malloc(n * sizeof(int))

Upvotes: 0

Views: 342

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

In this code snippet:

int *arr
int n
arr = malloc(n * sizeof(int));

there is set the value of the variable (pointer) arr with the address of the allocated memory.

In this statement:

*arr = malloc(n * sizeof(int));

the pointed object by the pointer arr that has the type int is set by the address of the allocated memory. However the pointer arr was not initialized and does not point to a valid object. Moreover the expression *arr has the type int while the right hand side expression has the type void *. So the compiler will issue an error.

You need to set the value of the pointer itself not the value of the pointed by the pointer object.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311018

arr is an int *, i.e. "pointer to int". When you dynamically allocate memory using malloc, you get a pointer that points to that memory, and should assign it to a variable, in this case, arr.

*arr (i.e., the dereference of arr) would just be an int. *arr is the value that arr points to, not the pointer (address) itself.

Upvotes: 1

Rob
Rob

Reputation: 15150

Because in the first example you are making arr the pointer to the memory. In the second example you are making what arr is pointing to the pointer to the memory allocated.

In other words, you declared arr as a pointer. Malloc returns a pointer to allocated memory. So you "fill" arr with that value. In your second example, you are filling *arr--what arr is pointing to--with the value returned by malloc.

Upvotes: 2

Related Questions