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);
}
In your
getSize()function,stris a pointer. Thereforesizeof(str)returns the size of a pointer. (which is 8 bytes in this case)In your
main()function,stris an array. Thereforesizeof(str)returns the size of the array.This is one of the subtle differences between arrays and pointers.