Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of character array and size of character pointer

Tags:

c

char

sizeof

I have a piece of C code and I don't understand how the sizeof(...) function works:

#include <stdio.h>

int main(){
   const char  firstname[] = "bobby";
   const char* lastname = "eraserhead";
   printf("%lu\n", sizeof(firstname) + sizeof(lastname));
   return 0;
}

In the above code sizeof(firstname) is 6 and sizeof(lastname) is 8.

But bobby is 5 characters wide and eraserhead is 11 wide. I expect 16.

Why is sizeof behaving differently for the character array and pointer to character?

Can any one clarify?

like image 359
user2416871 Avatar asked Jun 23 '13 11:06

user2416871


People also ask

What is the size of character array?

Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.

What is the size of character pointer?

Size of Character Pointer The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.

What is the size of a pointer to an array?

The pointer ptr, and all pointers, are 8 bytes, because they hold addresses, which are 8 bytes, or 64 bits. Assigning any address to an array variable is not allowed.

What is the difference between char pointer and char array?

For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string.


1 Answers

firstname is a char array carrying a trailing 0-terminator. lastname is a pointer. On a 64bit system pointers are 8 byte wide.

like image 166
alk Avatar answered Sep 27 '22 23:09

alk