Pointer, copy string a to string b

Beginners to learn C language, record the doubts and explanations along the way, welcome to point out mistakes, and welcome to discuss:

copy string a to string b

code show as below

//将字符串a复制给b 
#include <stdio.h>
int main()
{
    
    
	char a[] = "i love china ! ", b[100], * p1, * p2;
	int i = 0;
	p1 = a;
	p2 = b;
	for (; *p1 != '\0'; p1++, p2++)
	{
    
    
		*p2 = *p1;
	}
	*p2 = '\0';//记得给p2加上'\0'
	for (; b[i] !='\0'; i++)
	{
    
    
		printf("%c", b[i]);
	}
}

After finishing, I thought of several questions:
1. Has *p2 been overwritten? How did it pass to array b before that?
2. Can you use pointer variables to output? ?

After trying to change it,
I found that this is also possible:

#include <stdio.h>
int main()
{
    
    
	char a[] = "i love china", b[100], * p1, * p2,*p3;
	int i = 0;
	p1 = a;

	p2 = b;
	p3 = p2;
	for (; *p1 != '\0'; p1++, p2++)
	{
    
    
		*p2 = *p1;
	}
	*p2 = '\0';
	printf("%s", p3);
}

During debugging, it is found that the address of p3 is unchanged, but because we are operating on the address of p2, we directly change the content in the address of p2, and also change the content of p3. If only the value of p2 is changed, It will not affect p3.

In the same way, the same is true for the operation of b in the first program, changing the content in the address of b

Guess you like

Origin blog.csdn.net/zzzlueng/article/details/100104257