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