Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sizeof() work for char* (Pointer variables)? [duplicate]

Tags:

c

I have a C code:

char s1[20];
char *s = "fyc";
printf("%d %d\n", sizeof(s1), sizeof(s));
return 0;

It returns

20 8

I'm wondering how does the 8 come from, thanks!

like image 336
cloudyFan Avatar asked Jun 25 '13 13:06

cloudyFan


1 Answers

sizeof(s1) is the size of the array in memory, in your case 20 chars each being 1 byte equals 20.

sizeof(s) is the size of the pointer. On different machines it can be a different size. On mine it's 4.

To test different type sizes on your machine you can just pass the type instead of a variable like so printf("%zu %zu\n", sizeof(char*), sizeof(char[20]));.

It will print 4 and 20 respectively on a 32bit machine.

like image 92
Nobilis Avatar answered Sep 20 '22 22:09

Nobilis