指针语法混乱

Pointers Syntax Confusion

你好,我需要编写一个使用过的定义函数,通过它我需要提取指定数量的字符,虽然我能够做到这一点,但我有一个疑问,我没有得到预期的结果 o/p .

我使用了下面的代码,它给了我预期的 o/p

#include <stdio.h>

int xleft(const char *s, char *t, int offset)
{
    int i;

    for(i=0;i<offset;++i)
    {
        *(t+i)=*(s+i);  // t[i]=s[i] also worked  which I guess is the 
                        //syntactical sugar for it. Am I rt ? 

    }
    t[i+1]='[=10=]';
    return 1; 
}

int main()
{
    char mess[]="Do not blame me, I never voted VP";
    char newmess[7];
    xleft(mess,newmess,6);
    puts(newmess);
    return 0;
}

但是我无法理解为什么我在编写这样的代码时没有得到 o/p

#include <stdio.h>

int xleft(const char *s,char *t, int offset)
{
    int i;

    for(i=0;i<offset;++i)
    {
        *t++=*s++;
    }
    t[i+1]='[=11=]';

    return 1; 
}
int main()
{
    char mess[]="Do not blame me, I never voted VP";
    char newmess[7];
    xleft(mess,newmess,6);
    puts(newmess);
    return 0;
}

在新代码中,t[i+1](大约)等同于旧代码中的(t+i)[i+1](或t[i + i + 1])。

t[i]=s[i] also worked which I guess is the syntactical sugar for it. Am I rt ?

是的,你是对的s[i] = *(s+i);

在第二个代码片段中你正在移动你的指针 t 所以现在就做

*t = '[=10=]';

而不是

t[i+1] = '[=11=]'; /* Which is array out of bound access */
*(t+i)=*(s+i);  // t[i]=s[i] also worked  which I guess is the 
                   //syntactical sugar for it. Am I rt ? 

你确实是。 pointer[index],在 C 中,等同于 *(pointer + index).

然而,它与此不同:*t++=*s++;。在这里,您正在更改您的实际指针。因此,指针 t 的新值将是 t + i。这就是为什么t[i + 1],以t的原始值,变成了*(t + i + i + 1),这绝对不是你想要的。