The C language does not have the string type., Usually through the character pointer or character array operations. The difference between pointers and arrays is not mentioned here.
First, describeProgramThe distribution of variables in the memory.
Global variables are stored inData SegmentLocal variables are stored inStackThe variables dynamically allocated by malloc are stored inHeap. For the difference between stack and stack, please google.
The following is based on a specific program.
Code
# Include < Stdio. h >
# Include < Stdlib. h >
# Include < String . H >
Char * S1, * S2, * S3;
Void Test ()
{
Char * P1 = " ABC " ;
Char * P2, P3 [ 10 ];
P2=Malloc (10);
Strcpy (P2,"ABC");
Strcpy (P3,"ABC");
Printf ( " Static address: % P \ n " , & ( " ABC " ));
Printf ( " P1 address: % P \ n " , P1 );
Printf ( " P2 address: % P \ n " , P2 );
Printf ( " P3 address: % P \ n " , P3 );
S1 = P1;
S2 = P2;
S3 = P3;
}
Int Main ( Void )
{
Test ();
Printf ( " S1 = % s \ n " , S1 );
Printf ( " S2 = % s \ n " , S2 );
Printf ( " S3 = % s \ n " , S3 );
Return 0 ;
}
Three methods are used to assign values to strings.
1.
Char *P1= "ABC";
Here we are afraid that P1 points to a constant string "ABC", which is stored in the data segment for global use.
2.
Char *P2;
P2=Malloc (10);
Strcpy (P2,"ABC");
P2 is based on the dynamic memory allocation through malloc. It is stored in the heap and can be used globally. Generally, it is free after use. Otherwise, memory leakage will occur.
3.
Char P3 [10];
Strcpy (P3,"ABC");
P3 is the array name. The variables generated in this way are stored in the stack and the scope is local.
After the test function is called, the strings defined by P3 are released because they are stored in the stack. The strings pointed to by P1 and P2 are not stored in the data segment and heap, will not be released.
That's why printf ("S3 = % s \ n", S3); do not print "ABC.
Finally, the execution result of the program is given:
Static Address: 0x80485cc
P1 address: 0x80485cc
P2 address: 0x9ffc008
P3 address: 0xbffded10
S1 = ABC
S2 = ABC
S3 = (Í,
The above is my personal understanding. please correct me if something is wrong!
-------------
Walking down the fallen leaves, pursuing my dream