Kevin Hu
Kevin Hu

Reputation: 67

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);
}

Upvotes: 5

Views: 7370

Answers (2)

Mysticial
Mysticial

Reputation: 471559

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.

Upvotes: 7

ta.speot.is
ta.speot.is

Reputation: 27214

Different types, different sizes.

In main, str is a char[6]. In getSize str is a const char *. A pointer is (on a 64-bit platform) 8-bytes, so (given that sizeof(char) = 1):

6/1 = 6
8/1 = 8

Upvotes: 2

Related Questions