user4418808
user4418808

Reputation:

Pointers Syntax Confusion

Hello I need to write a used defined function through which I need to extract specified no of characters, Although I am able to do this but I have one doubt through which I am not getting the expected o/p.

I used the following code which gives me the expected 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;
}

But I am not able to understand why I am not getting the o/p when I write the code like this

#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;
}

Upvotes: 0

Views: 84

Answers (3)

user3079266
user3079266

Reputation:

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

Indeed you are. pointer[index], in C, is equivalent to *(pointer + index).

However, it's not the same as this: *t++=*s++;. Here, you are changing your actual pointers. So, the new value of the pointer t will be t + i. That's why t[i + 1], in terms of the original value of t, becomes *(t + i + i + 1), which is definitely not what you want.

Upvotes: 1

Gopi
Gopi

Reputation: 19874

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

Yes you are right s[i] = *(s+i);

Int the second code snippet you are moving your pointer t so now just do

*t = '\0';

instead of

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

Upvotes: 4

William Pursell
William Pursell

Reputation: 212584

In the new code t[i+1] is (approximately) equivalent to (t+i)[i+1] (or t[i + i + 1]) in the old code.

Upvotes: 0

Related Questions