pmv*_*rma 5 c pointers memory-management
好吧,我是C的新手.我想知道我的头衔.
假设我将指针声明如下,
char *chptr1;
char **chptr2;
int *i;
int **ii;
struct somestruct *structvar1;
struct somestruct **structvar2;
Run Code Online (Sandbox Code Playgroud)
然后,
char指针,
strdup()它本身分配内存,我们不必太关心它.指针指向事物.这取决于你让他们指出的东西.
你可以让他们没有初始化,不要使用它们:int * q;这有点傻.
你可以让它们指向存在的东西: int x; int * q = &x;
您可以在其中存储动态分配的内存的地址: int * q = malloc(29);
您首先需要了解的是,指针是用于存储内存地址或其他变量地址的变量。当您声明一个指针时,您是在为该指针分配内存,而不是为该指针指向的数据分配内存。例如,
char *ptr; //Here you allocated memory for pointer variable.
ptr = malloc(sizeof(char)); // allocated memory for the data pointed by ptr
Run Code Online (Sandbox Code Playgroud)
然后free()在使用内存后调用
free(ptr); // DE-allocates memory pointed by ptr and not variable ptr.
Run Code Online (Sandbox Code Playgroud)