简体   繁体   中英

C array pointer increment

Someone explain me this program. I've got a C code that makes use of pointer in array. For the below program

 #include<stdio.h>
    void function(char**);
    void main()
    {
        char *arr[] = {"ant","bat","cat","dog","egg","fly"};
        function(arr);
    }
    void function(char **ptr)
    {
        char *ptr1;
        ptr1 = (ptr+=sizeof(int))[-2];
        printf("%s\n",ptr1); 
    }

I'm getting the output as cat when using the index -2. Starting from the right corner the index value begins from 1. How does this happen. How does the index value behave this way rather than starting its index position from 0 from the left side. I expected the below values to be in the array

index value
0   ant
1   bat
2   cat
3   dog
4   egg
5   fly

But what the output was is

index value
-4  ant
-3  bat
-2  cat
-1  dog
0   egg
1   fly

How does this work?

Okay, you have some issues with your program but i'll try my best...

first, your issue lies with th line ptr1 = (ptr+=sizeof(int))[-2]; I can't understand what you expect it will do but what it actually does is ptr = ptr[4]; ptr1 = ptr[-2] ptr = ptr[4]; ptr1 = ptr[-2]

I tried to put out some debugging info to be more clear on the matter,

strings mapped in memory

0x400624 ant
0x400628 bat
0x40062c cat
0x400630 dog
0x400634 egg
0x400638 fly

to verify sizeof(int) is 4

at the start of function

*ptr - 0x400624 - "ant"

after your assignment to ptr1

*ptr - 0x400634 - "egg"
ptr1 = 0x40062c - "cat"

as you can see

  1. ptr now points to "egg" as the actual assignment to it was ptr = ptr[4]
  2. ptr1 is now pointing to "cat" as it is assigned ptr1 = ptr[-2]

You should readup on two things: "C order of evaluation" and also "pointer arithmatics"

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM