Sizeof for character array

why do i get results 6 and then 8 from the following code? I looked through the posts, but cannot find an exact match with my question. Thank.

#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);
}
+5
source share
2 answers

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

An main() strarray is in your function . Therefore, it sizeof(str)returns the size of the array .

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

+7
source

Different types, different sizes.

main, str char[6]. getSize str const char *. ( 64- ) 8 , (, sizeof(char) = 1):

6/1 = 6
8/1 = 8
+2

All Articles