没有输出,指针指向字符串

问题描述:

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?试图打印●当,不打印输出没有输出,指针指向字符串

+1

你的问题是什么? – munk 2013-03-07 15:26:02

你必须在字符串的好位置,显示之前重新定位你的指针(这样: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 

因为pq指针在while循环递增前加

p = a; 
q = b; 
再次

,他们没有指向任何更多在ab字符数组的开始

BTW和正像一句话:

可以

while(*p != '\0'){ 
    *q++ = *p++; 
} 
*q = '\0'; 

通过

while(*q++ = *p++); // more simple ;-) 

puts(p); //prints the string

这是由于的特定情况下只是运气替换这个代码集团情况。 pq都位于各自字符串的末尾。

+0

但是puts(p)如何从指针的起始处打印字符串 – Angus 2013-03-07 15:34:36

+0

printf打印的是什么? – UmNyobe 2013-03-07 15:41:27

+0

@Angus简而言之,给定一个字符串的addess,看跌期权()会,打印所有的字符,直到它遇到“\ 0”,将(),然后将这个为“\ n” – 2013-03-07 15:42:34

这里是你的代码固定

#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结束在你的空字符,这显然不是你想要的指点。

+0

耶正确。但是,它指向nul,puts()怎么能够打印整个字符串呢? – Angus 2013-03-07 18:02:22

+0

我不确定,当我在计算机上运行代码时,它不会输出整个字符串。 – naxchange 2013-03-07 18:03:34

+0

与printf()它没有输出整个字符串,但是当用puts(p)尝试时,得到了整个字符串的输出。 – Angus 2013-03-07 18:07:24