简体   繁体   中英

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))

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.

arr is an int * , ie "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 (ie, the dereference of arr ) would just be an int . *arr is the value that arr points to, not the pointer (address) itself.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM