c memory allocation problem

Both of the following can get hello:

#include<stdio.h>

#include<string.h>
#include<stdlib.h>

void GetMemory(char **p, int num)
{
*p = (char *)malloc(num); //The value pointed to by p changes, that is, the value of str change
}

int main()
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
return 0;

}



#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void *GetMemory()
{
char *p = (char *)malloc(100);
return p;
}

int main()
{
char *str = NULL;
str = GetMemory();
strcpy(str, "hello");
printf(str);
return 0;
}



Guess you like

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