On Sat, 06 Jan 2007 17:09:38 +0100, Johs <sd*@sdf.comwrote:
>In the below code I try to initialize the first 5 elements in an array
to 27:
Your code has serious errors. Why did you ignore the diagnostics your
compiler is required to produce? If you didn't see the diagnostics,
you need to adjust your compiler options until you do.
>
typedef int list[10];
Your misunderstanding of how this typedef works is the root cause of
your problem. list is now a synonym for the type array of 10 int.
>
void bob(list * p)
p is not an array of 10 int. It is a pointer to an array of 10 int.
In C notation, it is int(*)[10]. Based on the code in this function,
you want to remove the asterisk.
>{
int i;
for (i = 0; i < 5; i++)
{
p[i] = 27;
p[i] is not the i-th element of pop from main. Since p is a pointer
to an array, p[i] is actually the i-th array p points to. It is an
array. Arrays cannot appear on the left of the assignment operator in
an assignment statement. Who knows what kind of code you compiler
generated for this?
When you remove the asterisk from the parameter list, p will be an
array and p[i] will be the i-th element of the array. This element
will be an int and you can then assign the value to that int.
> }
}
int main()
{
list pop;
pop is an array of 10 int.
bob(&pop);
The argument of this function call has type pointer to array of 10
int, which does match the parameter of the function as you coded it.
Once you fix the definition of bob, you must remove the ampersand to
match. This statement will then "pass the array" to the function.
When an array are passed to a function, the argument is automatically
converted to the address of the first element with type pointer to
element type. This is the exact equivalent of passing &pop[0] and is
precisely what the modified bob will be expecting.
>
int y;
C89 does not allow declarations to follow statements. Put all your
declarations at the top of the block.
for (y = 0; y < 5; y++)
{
printf("pop[%d] = %d\n",y,pop[y]);
}
return 0;
}
But it only prints:
pop[0] = 27
pop[1] = 0
pop[2] = 0
pop[3] = 0
pop[4] = 0
What am I missing?
The fact that your code is not valid C.
Remove del for email