Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of pointer, pointer to pointer in C

Tags:

c

pointers

sizeof

How can I justify the output of the below C program?

#include <stdio.h>

char *c[] = {"Mahesh", "Ganesh", "999", "333"};
char *a;
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;

int main(void) {
    printf("%d %d %d %d ",sizeof(a),sizeof(c),sizeof(cp),sizeof(cpp));
    return 0;
}

Prints

4 16 16 4 

Why?

Here is the ideone link if you want to fiddle with it.

like image 479
Mahesha999 Avatar asked Aug 07 '26 16:08

Mahesha999


1 Answers

char *c[] = {"Mahesh", "Ganesh", "999", "333"};

c is an array of char* pointers. The initializer gives it a length of 4 elements, so it's of type char *[4]. The size of that type, and therefore of c, is 4 * sizeof (char*).

char *a;

a is a pointer of type char*.

char **cp[] = {c+3, c+2, c+1, c};

cp is an array of char** pointers. The initializer has 4 elements, so it's of type char **[4]. It size is 4 * sizeof (char**).

char ***cpp = cp;

cpp is a pointer to pointer to pointer to char, or char***. Its size is sizeof (char***).

Your code uses %d to print the size values. This is incorrect -- but it happens to work on your system. Probably int and size_t are the same size. To print a size_t value correctly, use %zu -- or, if the value isn't very large, you can cast it to int and use %d. (The %zu format was introduced in C99; there might still be some implementations that don't support it.)

The particular sizes you get:

sizeof a == 4
sizeof c == 16
sizeof cp == 16
sizeof cpp == 4

are specific to your system. Apparently your system uses 4-byte pointers. Other systems may have pointers of different sizes; 8 bytes is common. Almost all systems use the same size for all pointer types, but that's not guaranteed; it's possible, for example, for char* to be larger than char***. (Some systems might require more information to specify a byte location in memory than a word location.)

(You'll note that I omitted the parentheses on the sizeof expressions. That's legal because sizeof is an operator, not a function; its operand is either an expression (which may or may not be parenthesized) or a type name in parentheses, like sizeof (char*).)

like image 60
Keith Thompson Avatar answered Aug 10 '26 09:08

Keith Thompson