The specific questions are shown in the demo below:
#include <stdio.h>
void getheap (int *p)//p is a null address
{
p = malloc (sizeof (int) *);//p points back to the space allocated in the heap The c3/>}//form parameter int *p in the stack space, the function is released after it is finished, and the space allocated by malloc is also lost, and no return of the argument
int main ()
{
int *p = NULL; NULL is (void *) 0
printf ("p=%p\n", p);//p is a null address
printf ("p=%p\n", &p);//&p is the address of P itself
getheap (p //value passing, passing the null address to the formal parameter
p[0] = ten;
P[1] =;
printf ("p[0]=%d,p[1]=%d\n", p[0],p[1]);
Free (p);//p is not the first address of the space allocated in the heap, so free (p) also has a problem return
0;
}
Run:
Reason:
Corrected as follows:
#include <stdio.h>
void getheap (int **p)/p is the address
{
*p = malloc (sizeof (int) * 10) of S argument p; Assign the address of the space allocated in the heap to the argument p, that is, the argument p is the address of the allocated space in the heap after the end of the
}//function call, the value of the argument p is the first address of the allocated space in the heap,
int main ()
{
int *p = NULL;
Getheap (&P)//To pass the address of the pointer p itself to the formal parameter
p[0] = ten;
P[1] =;
printf ("p[0]=%d,p[1]=%d\n", P[0], p[1]);
Free (p); The value of the//p is the first address of the allocated space in the heap return
0;
}
Running normally:
Because:
Where 0x100 is the address of P itself, the **p p in the formal parameter is 0x100,
*p=malloc (int) *10), assuming that the allocated space address is 0x123, the equivalent of the p=0x123 in the main function, that is, p points to the first address of the allocated space;
int *GETHEAP2 ()//correct: Returns the address of the heap of the application
{return
malloc (MB);
}
Char *getstring ()//Error: Array is in the stack, after the function ends, the address disappears
{
char array[10]= "Hello";
return array;
}
Char getstring1 ()//correct: Returns the value, not the address, even if C is a variable in the stack, even if the address disappears
{
char c= ' a ';
return c;
}
const char *GETSTRING2 ()//correct: the constant is in the static area, the address always exists at the time the program is running
{
return "hello";//the address of a constant can be returned as a return value of a function
}
Char *getstring3 ()//correct:
{
static char array[10]= "Hello";//return array in static area
;
}
int main ()
{
int *p=null;
P=GETHEAP2 ()//correct
char *s=getstring ()//Error
char c=getstring1 ()//correct
const char *s1=getstring2 ();// Correct
const char *s2=getstring3 ();
return 0;
}