没有输出,指针指向字符串
问题描述:
int main(){
char a[80] = "Angus Declan R";
char b[80];
char *p,*q;
p = a;
q = b;
while(*p != '\0'){
*q++ = *p++;
}
*q = '\0';
printf("\n p:%s q:%s \n",p,q);
puts(p); //prints the string
puts(q); //doesnt print the string
return 0;
}
为什么字符串没有从p复制到q?试图打印●当,不打印输出没有输出,指针指向字符串
答
你必须在字符串的好位置,显示之前重新定位你的指针(这样:P = A和Q = B)。
int main(){
char a[80] = "Angus Declan R";
char b[80];
char *p,*q;
p = a;
q = b;
while(*p != '\0'){
*q++ = *p++;
}
*q = '\0';
p=a;
q=b;
printf("\n p:%s q:%s \n",p,q);
puts(p); //prints the string
puts(q); //doesnt print the string
return 0;
}
注意:您可能很幸运:puts(p); “打印字符串”这可能是因为a和b连续存储。如果你做了类似的事情:
char a[80] = "Angus Declan R";
char c[80] = {"\0"}; //example
char b[80];
puts(p);也不会打印任何东西。
答
printf("\n p:%s q:%s \n",p,q);
puts(p); //prints the string
puts(q); //doesnt print the string
因为p
和q
指针在while
循环递增前加
p = a;
q = b;
再次
,他们没有指向任何更多在a
和b
字符数组的开始
BTW和正像一句话:
可以
while(*p != '\0'){
*q++ = *p++;
}
*q = '\0';
通过
while(*q++ = *p++); // more simple ;-)
答
这里是你的代码固定
#include <stdio.h>
int main()
{
char a[80] = "Angus Declan R";
char b[80];
char *p,*q;
p = a;
q = b;
while(*p != '\0')
*q++ = *p++;
*q++ = '\0';
p = a;
q = b;
printf("\n p:%s q:%s \n",p,q);
puts(p);
puts(q);
return 0;
}
答
琴弦实际上是复制的,你可以看到,在最后输入此printf语句:
printf("\n a: %s b: %s \n", a, b);
但是,你忘了一些基本的东西有关++
运营商。当你写*q++ = *p++
,这是一样的文字:
q = q + 1;
p = p + 1;
*q = *p;
所以,通过你的循环,p和q结束在你的空字符,这显然不是你想要的指点。
你的问题是什么? – munk 2013-03-07 15:26:02