C Language Pointer Learning

Posted by spiritssight on Fri, 04 Feb 2022 18:35:43 +0100

1. References to strings

In C language programs, strings are stored in character arrays. To reference a string, you can use the following two methods

(1) Store a string in an array of characters, either by referencing one of the characters in the string with the array name and subscript, or by declaring the'%s'output string with the array name and format

[Example] Defines an array of characters in which the string "I love China!" is stored. Output the string and the eighth character

#include<stdio.h>
int main()
{
	char string[]="I love China!";               //Define Character Array
	printf("%s\n",string);                      //Output entire string
	printf("%c",string[7]);                     //Output eighth character
	return 0; 
}

Run result:

There is no specified length when defining the string array, but it is initialized, so its length is determined although only "I love China!" is stored! 13 characters, but it should be 14 because there is also a string terminator'\0', and the string name string represents the address of the first element of the character array. In fact, string[7] is * (string+7), and string+7 is an address that points to'C'.

(2) Point to a string constant with a character pointer variable and to a string constant with a character pointer variable

Output a string through a character pointer variable

#include<stdio.h>
int main()
{
	char *string="I love China!";               //Define character pointer variables and initialize 
	printf("%s\n",string);                      //Output entire string
	return 0; 
}

Run result:

There is no character array defined in the program, only a character pointer variable is defined, using the character constant "I love China!" Initialize it, C treats string constants as character arrays, opening up a string array in memory to store string constants, but the character array is unnamed, so it cannot be referenced by the array name, it can only be referenced by pointer variables.

Note: string is defined as a pointer constant and the base type is character type. Note that it can only point to one character type data, not to multiple character data at the same time, not to "I love China!" These are stored in strings (pointer variables can only store addresses), nor do they assign strings to *strings. Just put "I love Chian!" The address of the first character is assigned to the pointer variable.

//Pointer variables can be reassigned, for example
string = "I am a student."; 

%s is the format character used to output the string, which determines when the output character ends, i.e., when a string is input and output as a whole.

A character array name or character pointer variable can output a string, whereas a numeric array cannot output all its elements with an array name, for example:

int a[10];
.
.
.
printf("%d\n",a);

No, it outputs the address of the first element of the array. Element values of numeric arrays can only be output individually.

For character access in a string, you can use either the subscript method or the pointer method.

[Example] Copy string a as string b and output string b

#include<stdio.h>
int main()
{
	char a[]="I am a student.",b[20];                      //Define Character Array
	int i;
	for(i=0;*(a+i)!='\0';i++){                             //The value of a[i] is assigned to b[i] 
		*(b+i)=*(a+i);
	}
	*(b+i)='\0';
	printf("string a is:%s\n",a);                          //Elements of output array a 
	printf("string b is:");
	for(i=0;b[i]!='\0';i++){
		printf("%c",b[i]);
	} 
	
	return 0; 
}

Run result:

You can also use an array method to output the value of b, such as:

printf("string b is:%s\n",b);

Alternatively, you can access the string with a pointer variable, changing the value of the pointer variable to point to different characters in the string, as follows:

#include<stdio.h>
int main()
{
	char a[]="I am a boy.",b[20],*p1,*p2;                      //Define Character Array
	p1=a,p2=b;                                                 //p1,p2 point to the first element of the array a, b
	for(;*p1!='\0';p1++,p2++){                                  //p1,p2 self-addition 
		*p2=*p1;                                               //Assign the value that p1 points to to to p2   
	} 
	*p2='\0';
	printf("string a is:%s\n",a);
	printf("string b is:%s\n",b); 
	return 0; 
}

Run result:

2. Character pointer as function parameter

If you want to pass a string from one function to another, you can use either the character array name or the character pointer variable as an argument by address transfer. The content of the string can be changed in the called function, and the changed string can be referenced in the main function.

Use function calls to copy strings

[1] Use character array name as function parameter

#include<stdio.h>
void copy(char from[],char to[]);                       //Function declaration 
int main()
{
	char a[]="I am a teacher.";
	char b[]="You are a student.";
	printf("string a = %s\nstring b = %s",a,b);
	printf("\ncopy string a to string b:\n");
	copy(a,b);                                          //Use Character Array Name as Function Parameter
	printf("string a = %s\nstring b = %s",a,b); 
	return 0; 
}
void copy(char from[],char to[])                        //Parameters are character arrays 
{
	int i;
	while(from[i]!='\0'){
		to[i]=from[i];
		i++;
	}
	to[i]='\0';
}

Run result:

When the copy function is called, the addresses of the first characters of a and B are passed to the shape parameter group names from and to, respectively. Since the original length of array B is longer than that of array a, after copying the array a to array b, it cannot be completely overwritten. When output follows%s, it stops when it encounters'\0', and if it follows%c, it can also be output if it is not overwritten later. (

[2] Use character pointer variable as argument

#include<stdio.h>
void copy(char from[],char to[]);                       //Function declaration 
int main()
{
	char a[]="I am a teacher.";
	char b[]="You are a student.";
	char *from = a,*to =b;
	printf("string a = %s\nstring b = %s",a,b);
	printf("\ncopy string a to string b:\n");
	copy(from,to);                                          //Use Character Array Name as Function Parameter
	printf("string a = %s\nstring b = %s",a,b); 
	return 0; 
}
void copy(char from[],char to[])                        //Parameters are character arrays 
{
	int i;
	while(from[i]!='\0'){
		to[i]=from[i];
		i++;
	}
	to[i]='\0';
}

Can achieve the same goal

[3] Use character pointer variable as parameter and actual parameter

#include<stdio.h>
void copy(char *from,char *to);                                //Function declaration 
int main()
{
	char *a="I am a teacher.";                                //A is a char* pointer variable 
	char b[]="You are a student.";                            //b is an array of characters 
	char *p = b;                                              //Pointer variable p to the first element of the b array 
	printf("string a = %s\nstring b = %s",a,b);
	printf("\ncopy string a to string b:\n");
	copy(a,p);                                          //Use Character Array Name as Function Parameter
	printf("string a = %s\nstring b = %s",a,b); 
	return 0; 
}
void copy(char *from,char *to)                        //Parameters are character arrays 
{
	for(;*from!='\0';from++,to++){
		*to=*from;
	}
	*to='\0';
}

Procedure improvement:

copy Functions can also be overridden in a more refined way, as follows:
(1)
void copy(char * from,char * to)
{
	while((* to=*from)!='\0'){
		to++,from++;
	}
	
 } 
(2)
void copy(char *from,char* to)
{
	while(*from!='\0'){
		*to++=*from++;
	}
	*to='\0';
}
First put*from Assign to*toļ¼ŒThen add yourself
(3)
void copy(char * from,char * to)
{
	while((* to++=*from++)!='\0'){
		
	}
	
 }
(4)
Also available ascll Code to represent
{
	while(*from){                                  //And *from!='*from!='\ 0''Equivalence 
		*to++=*from++;
	}
	*to='\0';
  }  
(5)
These functions can also be written as
while(*to++=*from++);
Equivalent to:
while((*to++=*from++)!='\0');
(6)Also available for Loop statement
for(;(*to++=*from++)!='\0';);
Or:
for(;*to++=*from++;);
(7)You can also use the name of a character array as a function parameter
void copy(char from[],char to[])
{
	char *p1,*p2;
	p1=from,p2=to;
	while((* p2++=*p1++)!='\0'){
		
	}
	
 }  

3. Comparisons between using character pointer variables and character arrays

Strings can be stored and manipulated using character arrays and character pointer variables, but there is a difference between them:

(1) Character arrays consist of several elements, each with a character in it, and character pointer variables contain addresses (the address of the first character in the string), never strings in character pointer variables.

(2) Assignment method. You can assign to character pointer variables, but not to array names:

Character pointer variables can be assigned values in the following ways:
char *a;                        //A is a character pointer variable
a = "I love Chian!"             //Assigning the address of the first element of a string to a pointer variable is legal
 Character array names cannot be assigned in the following ways:
char str[14];
str[0]='I';                     //Assigning a value to a character array element is legal;
str="I love China!";            //Array names are addresses, constants, and cannot be assigned 

(3) The meaning of initialization, assigning initial values to character pointer variables:

char * a="I love China!";                   //Defines the character pointer variable a and assigns the address of the first element of the string to a
 Equivalent to:
char *a;                                    //Define character pointer variable a
a ="I love China!";                         //Assign the address of the first element of the string to a    
Initialize the array:
char str[14]="I love China!";               //Define an array of characters and assign an initial value
 Not equivalent to:
char str[14];                               //Define Character Array
str[]="I love Chian!";                      //Attempt to assign a string to each element in an array 

Arrays can be defined with initial values for each element, but not with assignment statements for the entire element in a character array

(4) Contents of the storage unit

Character arrays are compiled with storage units assigned to each element's value, while character pointer variables are assigned only one storage unit, such as the following usage

char *a;              //Define character pointer variable
scanf("%s",a);        //Attempting to enter a string from the keyboard so that a points to it, Error 

At compile time, pointer variables are assigned a storage unit, that is, the address of a has been specified, but a storage unit is an unexpected value that can cause system errors when input is made. Pointer variables should be specified to point to in time after they have been defined. For example:

char *a,str[10];                //Define character pointer variables and character arrays
a=str;                          //Make a point to the first element of str
scanf("%s",a);                  //Enter a string from the keyboard to store in a storage unit pointed to by a

Let a have a definite value before you enter it.

(5) The value of the pointer variable is changeable, while the character array name represents a fixed value (the address of the first element of the array) and cannot be changed.

Change the value of pointer variable

#include<stdio.h>
int main()
{
	char *a="I love China!";   
	a=a+7;
	printf("%s",a);                    
	return 0;
}

The result of the training is "China!"

The initial value pointed to by the pointer variable has changed, so the final output has changed. While the array name represents an address, it is a constant and its value cannot be changed. The following is an error:

char str[]={"I love China!"};
str = str+7;
printf("%s",str);

Topics: C