C language how to dynamically allocate space: malloc

Copyright: please indicate the source! https://blog.csdn.net/ZouHuiDong/article/details/90415482

General definition of variables will determine the size, but sometimes do not know the needs of users, such as ordering it, you do not know the number of users who might want to sort a few, so to be safe is often a big variable is defined when in fact the user may only need to give the number 5 sort, but you int k [1024]; to store the number to be sorted, causing great waste. Here are a function for dynamically allocating space: malloc

How to use malloc

prototype

extern void *malloc(unsigned int num_bytes);

head File

#include <stdlib.h>
#include <malloc.h>

statement

void *malloc(size_t size);

Note: This refers to the type void * is uncertain, that space can be allocated to the various types of variables.

Examples

int nSize;//要使用多大的空间
scanf("%d",&nSize);//获取要使用多大的空间

//动态分配空间
int *k;
k = (int*)malloc(nSize);//分配nSize大小的空间给k
//...执行其他代码
free(k);//释放掉分配给k的空间
k = NULL;//清空

The reason why the code to add (int *) malloc before because malloc originally void type, to be assigned to a variable of type int *, it is necessary to conduct the type of conversion. Similarly, malloc space may be allocated to other types of variables, but also converted to the appropriate type. malloc allocation of space to be emptied after use and then freed with free (variable name), otherwise the amount of memory will increase.
If the applicant fails
malloc also fail when the application space, then you can add a judge:

k = (int*)malloc(nSize);
if (k == NULL)//如果分配失败,因为如果分配成功了那k就有值。
		return 0;

Note that
malloc only allocates memory, memory allocation will not be initialized, the value assigned to the memory is random.
If the allocated memory is not a variable (such as malloc (nSize)) but has a specific value, you should write:

k = (int*)malloc(sizeof(int) * 64);//64是要分配的空间,如果是分配给其他类型的变量,其中的sizeof的参数也要有所改变。

Guess you like

Origin blog.csdn.net/ZouHuiDong/article/details/90415482