声明为指针的每个变量都必须分配内存吗?

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)

然后,

  1. 在将数据存储到每个变量之前,是否需要为每个变量分配内存?
  2. 当我不需要为它们分配内存时,有什么特殊情况吗?为此,我知道一个char指针, strdup()它本身分配内存,我们不必太关心它.
  3. 欢迎任何进一步的建议.

Ker*_* SB 9

指针指向事物.这取决于你让他们指出的东西.

  • 你可以让他们没有初始化,不要使用它们:int * q;这有点傻.

  • 你可以让它们指向存在的东西: int x; int * q = &x;

  • 您可以在其中存储动态分配的内存的地址: int * q = malloc(29);

  • +1表示简单的答案,但最后一个例子看起来真的不像你在现实世界中应该使用的任何东西.像`int*q = malloc(sizeof(*q));`或`int*q = malloc(sizeof(int));`似乎更合适. (5认同)

Chi*_*nna 5

您首先需要了解的是,指针是用于存储内存地址或其他变量地址的变量。当您声明一个指针时,您是在为该指针分配内存,而不是为该指针指向的数据分配内存。例如,

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)