-3

My question is: why is there a "--p", from what I understand the "++p"function serves to climb a number of imaginary array pointer, but the "--p" is for that? I realized that without it the code letters are not shown but did not understand how this works. thanks and even more

code :

#include <stdio.h>

using namespace std;

int main()
{
    char* p = new char [12];
    *p=0x48;
    ++p;
    *p=0x65;
    ++p;
    *p=0x6c;
    ++p;
    *p=0x6c;
    ++p;
    *p=0x6f;
    ++p;
    *p=0x20;
    ++p;
    *p=0x57;
    ++p;
    *p=0x6f;
    ++p;
    *p=0x72;
    ++p;
    *p=0x6c;
    ++p;
    *p=0x64;
    ++p;
    *p=0x0;
    ++p;

    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;
    --p;

    printf(p);
    delete p;

    return 0 ;

}
4

3 回答 3

1
char *p = _ _ _ _ _ _ _ _ _ _ _ _
         /\

最初p指向数组的开头,如图所示

p++ == ++p == (p = p+1) 

因此,这会将指针向右移动一位。

p-- == --p == (p = p-1) 

因此,这会将指针向左移动一位。

于 2013-08-20T01:17:44.433 回答
0

这些是为了p指出刚刚编写的字符串的开头。

有几种方法可以改善这一切,例如:

p -= 12;  // instead of all the --p

或者

strcpy (p, "\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64");

或者

p = new string ("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64");

甚至:

*p++ =0x48;
*p++ =0x65;
*p++ =0x6c;
*p++ =0x6c;
*p++ =0x6f;
*p++ =0x20;
*p++ =0x57;
*p++ =0x6f;
*p++ =0x72;
*p++ =0x6c;
*p++ =0x64;
*p    =0x0;

p -= 11;

或者,直接直观:

int main ()
{
     printf ("Hello World");
     return 0;
}
于 2013-08-20T01:15:24.983 回答
0

我非常愿意这样做:

char *p = new char[13];
char *q = p; 
*p=0x48;
++p;
*p=0x65;
++p;
*p=0x6c;
++p;
*p=0x6c;
++p;
*p=0x6f;
++p;
*p=0x20;
++p;
*p=0x57;
++p;
*p=0x6f;
++p;
*p=0x72;
++p;
*p=0x6c;
++p;
*p=0x64;
++p;
*p=0x0;
++p;

printf(q);

但本质是,由于它移动--p需要“反向回到开头”,作为已完成设置字符串的 ++p 的计数器。

[并且不运行它,我可以看到它打印Hello World]

于 2013-08-20T01:18:14.653 回答