Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() function in C [duplicate]

Tags:

arrays

c

pointers

main()
{
char a[] = "Visual C++";
char *b = "Visual C++";
printf("\n %d %d",sizeof(a),sizeof(b));
printf("\n %d %d",sizeof(*a),sizeof(*b));
}

sizeof(a) gives me output: 11 ( that is length of the string)

Why is it so ?
Why isn't the output sizeof(a)=4 since when I try to print a it gives me an address value and hence an integer?

like image 686
Shivaji_Vidhale Avatar asked Jan 29 '26 12:01

Shivaji_Vidhale


1 Answers

Whenever you refer to the name of the array in your program, It normally decays to a pointer to the first element of the array. One of the exception to this rule is the sizeof operator. So when you consider the following code.

int main()
{
   char a[] = "Visual C++";
   printf("sizeof(a)=%d\n",sizeof(a)); /* Here sizeof(a) indicates sizeof array */
   printf("a=%p",a); /* Here the array name, passed as an argument to printf decays into a pointer of type (char *) */
   return 0;
}
like image 138
Vivek Maran Avatar answered Jan 31 '26 01:01

Vivek Maran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!