本文介绍了简单的指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在下面的代码中,有人能告诉我* p ++和 p ++之间的区别吗?我可以看到两者都达到了相同的结果。 非常感谢! #include< iostream> using namespace :: std; int main(){ char * p =" test pointer"; 而(* p){ cout<< * p; * p ++; //<< - * p ++和p ++之间有什么区别(两个实现 相同的结果)? } cout << endl; 返回0; } 解决方案 p ++递增指针,就像你期望的那样* p ++首先取消引用 指针,然后递增它。由于解除引用的临时不是分配给任何东西的b $ b,它会被丢弃。 hth - jb (如果你想通过电子邮件回复,用x代替y) 在这种情况下没有差异。 如果你要做一个cout<< * p ++ 然后它会打印p'的当前字符然后 incr ptr * p得到值来自ptr ++ incr ptr的类型大小。 / ak 好​​的, p ++增加了指针 * p获取指针所指向的变量的内容 你可以写在你的循环中 cout<< * p ++<< endl; 由于*运算符的优先级,所以* p在p ++之前完成, 也许你会更清楚写一下(* p)++(不要在编码中使用这个... / b $ b这只是为了让你理解你应该在代码中编写* p ++) 也许复制两个字符串的例子; char * s1 =" test"; char * s2 =" blab"; for(unsigned int i = 0; i< strlen(s1); i ++) * s1 ++ = * s2 ++; 因此s1的内容成为s2的内容; 注意它们都是相同的大小,如果不是你可能有 未定义的行为。 但如果哟你想复制strign我会建议使用< string> 而不是char *。 HTH - Frane Roje 祝你有愉快的一天 从电子邮件中删除(* dele * te)以回复 Hi,In the following code, can someone tell me the difference between *p++ andp++ ? I can see both achieve the same result.Thanks a lot !#include <iostream>using namespace::std;int main() {char *p = "test pointer";while (*p) {cout << *p;*p++; // <<- What is the difference between *p++ and p++ (both achievethe same result) ?}cout << endl;return 0;} 解决方案p ++ increments the pointer, like you expect. *p ++ first dereferencesthe pointer, and then increments it. Since the dereferenced temporary is notassigned to anything, it is discarded.hth--jb(replace y with x if you want to reply by e-mail)in this context there is no diff.if you would for instance do a cout << *p++then it would print p''s current char and thenincr the ptr*p get the value from the ptr++ incr the ptr with whatever size of type it is./akOk,p++ increments the pointer*p gets the contents of the variable to which the pointer is pointing toYou could write in your loopcout<<*p++<<endl;Because of the precedence of the * operator so the *p is done before p++,maybe it would be more clear if you wrote (*p)++ (don''t use this in codingthis is just for you to understand you should write *p++ in your code)Maybe an example of copying two strings;char *s1="test";char *s2="blab";for(unsigned int i=0;i<strlen(s1);i++)*s1++=*s2++;So the content of the s1 becomes the content of the s2;Note that they are both the same size, if not you might haveundefined behavior.But if you want to copy strign I would reccomed using <string>rather than char*.HTH--Frane RojeHave a nice dayRemove (*dele*te) from email to reply 这篇关于简单的指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-02 05:25