Pointers as function parameters Note

#include <stdio.h>

void free_delete(int  *p)

{
if (NULL == p) return;
free(p);
p = NULL;

}

int main()
{ /*The content of p is released in the free_delete function, and the value of p has not changed or points to the address that has been released. */ int *p = (int*)malloc(sizeof(int));        *p = 1234; free_delete(p); if (NULL == p) { printf("p == NULL\n"); } else { printf("*p == %d\n",*p); }














}

[Jacob] Passing pointers in C is essentially passed by value, but the value is the address of the variable. For example: in the above example.

  • The value of p in main is 0x....4578, which is passed to the function free_delete, and the value of p in the function is still 0x....4578
  • In the function, the memory pointed to by p is released, and then the value of p is set to null. The original intention is to set the value of p in main to NULL, but this cannot be passed back. Because the value of p in the function is on the stack, after the call ends, the value of p in the function is destroyed. The p value in main is still 0x....4578
  • However, the content pointed to by the p value is accessed again in main. Because the content is destroyed, the output value is random data.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324759134&siteId=291194637