简体   繁体   中英

Why isn't the size of my array 4 bytes in C

char foo[3] = { 97, 98, 97 };
printf("%d",sizeof(foo));

After debugging it gives me a result of 3.

Why isn't the result 4?

foo[3] consists of 4 characters 0,1,2,3 right?

Size of char is 1 byte so why isn't foo 4 bytes?

Why isn't the result 1?

When i call foo it is the same as calling &foo[0] . So how do i know when i'm calling for whole array and when for the first character? like here sizeof(foo)

I think you're confused with array size and array indexing. If you declare an array a of size 3 with the line char a[3]; , it holds three elements, and those elements are accessed as a[0] , a[1] , and a[2] . Those are the only elements that exist in the array. a[3] would be out of bounds.

foo[3] consists of 4 characters 0,1,2,3 right?

No. The array of char , foo holds three elements: foo[0], foo[1], foo[2] . Since a char is always of size 1 (not necessarily a byte!) an array of three chars will therefore have a sizeof 3.

As for your second question, this SO question may shed some light on it.

Ok, I'll take this one question at a time...

Why isn't the result of sizeof(foo) 4?

It's because you've only set the size of the foo array to 3 in the first statement char foo[3] . There would be no reason to expect 4 as a result when you've explicitly defined the bound as 3 chars which is 3 bytes.

Why isn't the result 1?

You're correct in saying that in some cases , calling foo is the same as &foo[0] . The most relevant of these cases to your question is when being passed as a pointer into a function as a parameter. In the case of the sizeof function, when you pass in your foo array pointer, the function iterators throughout the memory block associated with that argued pointer and returns the total size, therefore not being 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM