Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a char* being treated the same as a char** in C?

I have the following test application:

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

int main(void){
    char buf[512];
    buf[0]= 0x1;
    buf[1]= 0x2;
    char *temp1 = &buf;
    char *temp2 = buf;
    char *temp3 = &buf[0];
    printf("temp1:%p, temp2:%p, temp3:%p\n",temp1,temp2,temp3);
    printf("0 = %d, %d, %d\n",temp1[0],temp2[0],temp3[0]);
    printf("1 = %d, %d, %d\n",temp1[1],temp2[1],temp3[1]);
    return;
}

It compiles with a warning:

gcc ./testptr.c -o testptr
./testptr.c: In function ‘main’:
./testptr.c:9: warning: initialization from incompatible pointer type

But when I run it, all three pointers behave the same.

./testptr
temp1:0x7fff3a85f220, temp2:0x7fff3a85f220, temp3:0x7fff3a85f220
0 = 1, 1, 1
1 = 2, 2, 2

I know that buf == &buf[0], but why does &buf == &buf[0]? Shouldn't &buf be a char**?

like image 369
austinmarton Avatar asked Oct 06 '11 02:10

austinmarton


2 Answers

All pointers behave the same because you declared all of them to be char*. C is statically typed so the type is bound to the variable and not the value.

Now that the behaviour part is explained, we only need to find out why they actually have the same value (as per the %p printf). Well, this is just an artifact of pointers being implemented as a memory address by GCC (the offsets and sizing that make a * differ from a ** are all handled by the type system/compiler behind the scenes). Do note that like any of the most suspicious stuff that gives out warnings, this is likely to be undefined behaviour or at the least, a bad practice :)

like image 122
hugomg Avatar answered Oct 03 '22 20:10

hugomg


Arrays are not pointers, although they can be used in much the same way. You happen to have found one aspect in which array and pointer semantics differ.

like image 27
Patrick87 Avatar answered Oct 03 '22 19:10

Patrick87