Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof for a character array

why do I get results 6, and then 8 by from the following code? I searched through the posts but cannot find an exact match of my question. Thanks.

#include <stdio.h>

void getSize(const char *str)
{
        printf("%d\n", sizeof(str)/sizeof(char));
}

int main()
{
        char str[]="hello";
        printf("%d\n", sizeof(str)/sizeof(char));
        getSize(str);
}
like image 757
Kevin Hu Avatar asked Jan 27 '12 22:01

Kevin Hu


People also ask

What does sizeof return for a char array?

sizeof() operator returns actual amount of memory allocated for the operand passed to it. Here the operand is an array of characters which contains 9 characters including Null character and size of 1 character is 1 byte. So, here the total size is 9 bytes.

Does a char * need a size in C?

As char 's size is always the minimum supported data type, no other data types (except bit-fields) can be smaller. The minimum size for char is 8 bits, the minimum size for short and int is 16 bits, for long it is 32 bits and long long must contain at least 64 bits.


1 Answers

In your getSize() function, str is a pointer. Therefore sizeof(str) returns the size of a pointer. (which is 8 bytes in this case)

In your main() function, str is an array. Therefore sizeof(str) returns the size of the array.

This is one of the subtle differences between arrays and pointers.

like image 128
Mysticial Avatar answered Sep 17 '22 21:09

Mysticial