4

The following code works exactly as expected, but the compiler gives me incompatible pointer type warning. A cast will solve this, but I really don't understand why this should be a warning. A pointer is an integer that is an address of a certain memory area, and in my example, v has got the address of d which is an integer and that seems all. Please help me understand this issue.

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

int main(void) {
    double *d;
    void **v;

    d = malloc(sizeof(double));
    *d = 1.1;
    printf("%.1f\n", *d);
    v = &d;
    *(double *)*v = 2.2;
    printf("%.1f\n", *d);
    return 0;
}
  • 6
    Pointers aren't arbitrarily convertible to one another. You can only convert to and from `void *`. – Kerrek SB Dec 18 '14 at 15:31
  • 5
    `void*` is a generic pointer type. `void**` is not. There is no generic pointer-to-pointer type. – Keith Thompson Dec 18 '14 at 15:37
  • 1
    To elaborate on @KeithThompson 's comment you might find this helpful http://stackoverflow.com/q/25427587/1240985 , trying to find more. Perhaps: http://www.nongnu.org/c-prog-book/online/x658.html , I have to re-read that one. – Morpfh Dec 18 '14 at 15:49

1 Answers1

2

I wanted to post this as a comment but I still don't have the reputation... :-/

One of the few things I can think of, is Pointer Arithmetic. It wouldn't work if all types of pointers were treated the same way. So, a pointer is not just a pointer, its type does matter.

For example, try this:

short s = 5;
int i = 6;
printf("s: 0x%X -> 0x%X\n", &s, (&s)+1);
printf("i: 0x%X -> 0x%X\n", &i, (&i)+1);

The output is:

s: 0x270A724E -> 0x270A7250                                              
i: 0x270A7248 -> 0x270A724C

Note how s shifts two addresses (4E to 50, because it's a short), and i shifts four (48 to 4C, because it's an int). With (&s)+1 we're asking to move one position of the type of the pointer. You could use the same thing to move through an array without using []. And that's the same reason why char *str makes you move one address when you make str++.

maganap
  • 2,414
  • 21
  • 24