Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sizeof(*"327") return 1 instead of 8 on a 64 bit system?

Tags:

 printf("%lu \n", sizeof(*"327")); 

I always thought that size of a pointer was 8 bytes on a 64 bit system but this call keeps returning 1. Can someone provide an explanation?

like image 378
lordgabbith Avatar asked Oct 12 '17 08:10

lordgabbith


People also ask

What does sizeof return in C array?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What does sizeof pointer return?

The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.

What is the format specifier for sizeof in C?

The sizeof(variable) operator computes the size of a variable. And, to print the result returned by sizeof , we use either %lu or %zu format specifier.

How sizeof is an operator?

The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.


2 Answers

Putting * before a string literal will dereference the literal (as string literal are array of characters and will decay to pointer to its first element in this context). The statement

printf("%zu \n", sizeof(*"327"));  

is equivalent to

printf("%zu \n", sizeof("327"[0]));   

"327"[0] will give the first element of the string literal "327", which is character '3'. Type of "327", after decay, is of char * and after dereferencing it will give a value of type char and ultimately sizeof(char) is 1.

like image 144
haccks Avatar answered Sep 28 '22 05:09

haccks


The statement:

printf("%lu \n", sizeof(*"327")); 

actually prints the size of a char, as using * dereferences the first character of string 327. Change it to:

char* str = "327"; printf("%zu \n", sizeof(str)); 

Note that we need to use %zu here, instead of %lu, because we are printing a size_t value.

like image 32
Marievi Avatar answered Sep 28 '22 05:09

Marievi