#define _CRT_SECURE_NO_WARNINGS
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int main()
{
char buf1[100] = { 0 };
char buf2[100] = { 0 };
char *p1 = buf1;
char *p2 = buf2;
strcpy(p1, "abcdefg");
printf("p2,%d\n", p2);
printf("buf2,%d\n", buf2);
while (*p1 != '\0')
{
*p2++ = *p1++;
}
printf("p2,%d\n", p2);
printf("buf2,%d\n", buf2);
printf("p2,%d\n", *p2);
printf("buf2,%d\n", *buf2);
system("pause");
有这样代码,为什么运行出来的结果是这样 p2和buf2地址会差7?
因为你在while循环中对p2做了自加运算,最终p2指向了字符串的末尾\0,而buf2一直没动,一直指向字符串的开头,自然会差7。
p2和p1都已经++了7次了吧。。。
p2是指针,在p1将所指的值一个个的赋给p2所指的内存单元后,p2向后移动,值增加7(有七个字符,每个字符占一个地址值) ,buf2只是
数组的首元素地址,不变,只有p2变了,所以大7