Notes on learning string knowledge in C
1: In C, we say "H" is a string with two bytes in total, followed by a '\ 0' pseudo zero Terminator.
'H' is a number. Verify with the following program.
#include
int main(void){printf("%d %d\n",sizeof("c"),sizeof('s'));}
2: String creation process
#include
int main(void){char * p = "hello world!";printf("%s\n", p);}
Here, Why can a string be assigned to a char * type pointer variable?
1: When we write hello, it tells the compiler to store 6 bytes in the read-only data segment.
2: the value of the "hello" expression represents the address of the first character of the string.
# Include
Int main (void) {char * p = "world"; // print the code to show that the string represents an address. Printf ("% s \ n", p); printf ("% c \ n", * ("hello"); return 0 ;}
// The Data printed out of the border is growing # include
Void func (void) {int * p = "hello! "; Write (1, p, 10);} int main (void) {int * q =" hello world "; func (); return 0 ;}
3: Passing parameters in the string:
#include
int main(void){char * p = "hello word! %d\n";printf(p,5);return 0;}
4: Modify the string content
# Include
Int main (void) {char * p = "hello word! \ N "; p [0] = 'H'; // This will cause compilation problems, because the content of the read-only data segment cannot be changed to printf (" % c \ n ", p [0]); // printf (p, 5); return 0 ;}
// If we want to modify the content in the read-only string, we need to put the data in an array, which is equivalent to copying the content in the read-only data segment.
For example
#include
int main(void){char * p = "hello word!\n"; p[0] = 'H';printf("%c\n",p[0]);return 0;}
5: Evaluate the valid byte length of a string:
# Include
# Include
Int main (void) {char * p = "hello"; // p [0] = 'H'; // printf ("% c \ n ", p [0]); // printf (p, 5); char a [] = "hello"; // strlen () this function is used to evaluate the valid byte length of a string. printf ("% ld \ n", strlen (a); return 0;} is determined based on the pseudo-zero end time ;}