Gotchas: Difference between revisions

m
Line 187:
 
The gotcha is that <code>sizeof</code> can't be used to calculate anything at runtime. The <code>sizeof</code> operator merely provides a compile-time constant using the information you provided to the compiler about that variable. For arrays, the data type of the array and the number of elements are multiplied together to give the size. C uses this information to know how many bytes to reserve on the stack for the array, but the size isn't stored anywhere with the array. As far as the CPU knows, the fact that the above function's return value is the size of the array is merely a coincidence.
 
Put another way, <code>sizeof</code> is just a <code>#define</code> that doesn't pollute your namespace:
<syntaxhighlight lang="C">int foo()
{
#define size_of_bar 20 //the sizeof operator is the same as doing this essentially.
 
char bar[size_of_bar];
return size_of_bar;
}</syntaxhighlight>
 
 
 
As a result of this subtle nuance, many new C programmers will write the code below thinking that it will return a value corresponding to the number of elements the array was originally declared with.
<syntaxhighlight lang="C">int gotcha(char bar[])
{
Line 194 ⟶ 205:
}</syntaxhighlight>
 
As a result of this subtle nuance, many new C programmers will write the above code thinking that it will return a value corresponding to the number of elements the array was originally declared with. This is not the case, as when passing an array to a function, you're actually passing <i> a pointer to element 0 of that array</i>. Therefore, any size information about that array is lost. In <code>main</code> we might write
<syntaxhighlight lang="C">myArray[40];
int x = gotcha(myArray);</syntaxhighlight>
1,489

edits