c - 指针语法困惑

标签 c arrays pointers

你好,我需要编写一个使用过的定义函数,通过它我需要提取指定数量的字符,虽然我能够做到这一点,但我有一个疑问,通过它我没有得到预期的 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]='\0';
    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]='\0';

    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]=s[i] also worked which I guess is the syntactical sugar for it. Am I rt ?

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

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

*t = '\0';

代替

t[i+1] = '\0'; /* Which is array out of bound access */

关于c - 指针语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28208601/

相关文章:

c++ - OpenSSL 和信号

c - C 中的非法汇编指令

python - 将数组写入文本文件,每行中具有最大元素数量

javascript - 每隔一段时间将项目从 JavaScript 数组中逐一输出到 HTML 文本

c - 结构问题: initialization makes integer from pointer without a cast

c++ - 试图理解指针和双指针

c - 算法查找 2 个字符串中常见字符的数量

c - 如何修改已传递给 C 函数的指针?

python - 一个 numpy 数组的 Softmax 函数

C++ 指针和对象