1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

void pointer increment

Discussion in 'C' started by girish4c, May 3, 2010.

  1. girish4c

    girish4c New Member

    Joined:
    May 3, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    hi all,,
    if i increase void pointer, in gcc compiler am not getting any error but same its error in VC compiler..


    so please let me know wat i need consider as per standards in C?

    int i;

    void *ptr;
    ptr=&i;

    ptr++; //ERROR IN VC BUT NO ERROR IN GCC
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    If you increment a pointer to a thing, the pointer is not just increased by 1 byte but by the size of that thing. So a pointer to char will increment by 1 char, a pointer to int will increase by sizeof(int) (typically 4 bytes), a pointer to a struct S will increase by sizeof (struct S), so that the pointer points to the "next" object, which is more use than it pointing to the next byte in memory.

    Code:
    int i[10], *pi;
    char j[10], *pj;
    void *k;
    k=&i[0];
    pi=&i[0];
    pi++; k++; // should both increase by the same?
    k=&j[0];
    pj=&j[0];
    pj++; k++; // should both increase by the same?
    
    But void* does not point to anything with a fixed size, and sizeof(void) is meaningless, so the compiler cannot tell in general what it points at, so it cannot determine by how much it should increment. So I think the most appropriate behaviour is to throw an error. But maybe this is left undefined by the Standard, in which case both behaviours would be correct.

    In the code above you can tell from the context what k points to. But if we passed k into a function then the compiler has no way at all to determine what sizeof(*k) is.

    Googling around (which you should try some time rather than assuming you're the first person ever in the history of computer programming to have thought of this), it seems the VC++ behaviour corresponds to ANSI standard behaviour so maybe VC++ is ANSI standard by default and gcc is not. Try enabling ANSI standard compliance for gcc, there's probably a flag (and before you ask, try googling it and/or RTFM), and this should result in an error from gcc.
     

Share This Page