简体   繁体   中英

C - Declaring variables and calling malloc

I dont get why do you have to do both. Isnt malloc creating dynamic memory for you? Then why do we have to state for example "int " in the beginning when later i will be mallocing that variable. Im new to malloc, sorry if this question has an obvious answer.

Example:

In the main :

int *p;

Then later in the function:

int *p = malloc(1000 * sizeof(int));

Isnt malloc creating dynamic memory for you?

It does. However, you need to be able to hold the address of that memory somewhere, too.

int *ptr = malloc(1000 * sizeof(int));
...
free(ptr); // Once you are done, you need to release the memory by calling free

The address is stored in a pointer ptr , which needs a small amount of memory to be stored. You use that pointer to reference the memory that you have allocated.

There is a big difference between the following two definitions:

int i;
int *pI;

i an int . It has a memory location that you can write a value to.

pI , however, is not an int . It is a pointer to an int . It's value is an address. You cannot write a value to the memory location it's pointing to until you point it to a valid memory location big enough to hold an int . For example:

pI = &i;
*pI = 10;

You can create a generic pointer by using the keyword void but cannot dereference a void pointer. The compiler needs to know the date type in order to dereference a pointer.

int i;
void *pV;

pV = &i;
*(int *)pV = 10;

如果在main函数中又在函数中再次声明int * p,那么您将获得两个具有不同作用域的指针,则in函数中的p仅在输入函数时才在作用域中,而在函数返回时将不相关,除非您的函数返回函数的地址。函数的p到main。

In the specific case of an int you probably do not want to create memory space dynamically. You only would want to do this when you do not know the worst case scenario of you memory usage.

It would be a different story entirely if you would create a int pointer. More information can be found in this post

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