Jump to content

Gotchas: Difference between revisions

m (→‎{{header|J}}: another gotcha - including a rosettacode wiki gotcha)
Line 166:
if(a==b){} //runs the code in the curly braces if and only if the value of "a" equals the value of "b".</syntaxhighlight>
 
===ArraysArray Indexing===
Arrays are declared with the total number of elements in an array.
<syntaxhighlight lang="C">int foo[4] = {4,8,12,16};</syntaxhighlight>
Line 177:
int y = foo[3]; //y = 16
int z = foo[4]; //z = ?????????</syntaxhighlight>
 
===The sizeof operator===
One of the most common misunderstandings about C arrays is the <code>sizeof</code> operator.
<syntaxhighlight lang="C">int foo()
{
char bar[20];
return sizeof(bar);
}</syntaxhighlight>
 
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.
 
 
<syntaxhighlight lang="C">int gotcha(char bar[])
{
return sizeof(bar);
}</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>. In <code>main</code> we might write
<syntaxhighlight lang="C">myArray[40];
int x = gotcha(myArray);</syntaxhighlight>
 
which is actually the same as
<syntaxhighlight lang="C">myArray[40];
int x = gotcha(&myArray[0]);</syntaxhighlight>
 
As using <code>sizeof</code> on a memory address returns the number of bytes that the CPU's instruction pointer register can hold, you'll get the same return value from <code>gotcha</code> regardless of how many elements the array has. When C programmers talk about "arrays decaying into pointers" this is what they're referring to.
 
=={{header|J}}==
1,489

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.