Why does this program go wrong?

-sharpinclude<malloc.h>
-sharpinclude<stdio.h>
-sharpinclude<stdlib.h>
void init(int *p)
{
    p=(int *)malloc(sizeof(int));
}
int main()
{
    int *p;
    init(p);
    *p=4;
    printf("%d",*p);
    return 0;
}
C
Sep.03,2021

because the p allocated by init is not a pointer passed in the past, but a copied p, so the p in main is not allocated to memory, you need to pass the address of the pointer to the past.


in a sense, c is passed only by value. So to change the value of a variable outside the function, you need to use a pointer to that variable. So as far as the problem is concerned, if you want to change the value of pointer p in main in the init function, you need to pass a pointer to pointer p, that is, the char type.

Menu