intentionally-left-nil
intentionally-left-nil

Reputation: 8316

Preventing compilation of void** pointer arithmetic in C

This is the same concept as Pointer arithmetic for void pointer in C except my data type is a void** instead of a void*

#include <stdlib.h>
#include <stdio.h>

int main() {
    int foo [] = {1, 2};
    void* bar = &foo;
    void** baz = &bar;
    void** bazplusone = baz + 1;

    // cast to void* to make printf happy
    printf("foo points to %p\n", (void*)foo);
    printf("baz points to the address of bar and is %p\n", (void*)baz);
    printf("bazplusone is an increment of a void** and points to %p\n",(void*)bazplusone);
    return 0;
}

which results in the following output for my version of gcc:

foo points to 0x7ffeee54e770
bar is a void* cast of foo and points to 0x7ffeee54e770
baz points to the address of bar and is 0x7ffeee54e760
bazplusone is an increment of a void** and points to 0x7ffeee54e768

I have two questions:

  1. Is this legal according to the C standard?
  2. Assuming #1 is false, is there a way to generate a compiler error? Neither -pendandic-errors nor -Wpointer-arith complains about this small program

Upvotes: 0

Views: 117

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54355

I misunderstood what you were doing at first. I thought you were doing math on a void*. That is not allowed by the C Standard, but is allowed by a GCC (and clang) extension that treats it as math on a char*.

However, you are doing math on a void** which is perfectly OK. A void* is the size of a pointer and is not an undefined value. You can make arrays of void*s and you can do pointer math on a void** because it has a defined size.

So you will never get a warning for void** math because it is not a problem.

Upvotes: 2

Related Questions