-5
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)

Nymous
  • 3
  • 4

3 Answers3

0

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.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
0

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.

Community
  • 1
  • 1
pateryan
  • 36
  • 3
0

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.

m_callens
  • 6,100
  • 8
  • 32
  • 54
  • That's not the only main case. Arithmetic expressions come to mind as well. In fact, arrays decays to pointers more often than not. An to nitpick `sizeof` is not a function, it's an operator, and it does no iteration. – StoryTeller - Unslander Monica Jan 29 '17 at 22:14
  • @StoryTeller yes, you're right. I only mention the function parameter example because it was relevant to his question – m_callens Jan 29 '17 at 22:14