Reputation: 21
When I create a new array using main array's base address I write this:
main()
{
int a[]={0,1,2,3,4,5,6,7,8,9};
display(a);
}
display(int anew[])
{
int i;
for(i=0;i<10;i++)
printf("%d ",anew[i]);
}
Why can I not do the same when trying to create a new int variable using address like this?
main()
{
int a=7;
display(&a);
}
display(int b)
{
printf("%d ",b);
}
Upvotes: 1
Views: 118
Reputation: 561
Because display(int anew[])
is the same as display(int *anew)
but display(int *b)
is not the same as display(int b)
. In C, when passed in a function, an array 'degenerates' into a pointer (to the first element). No such thing happens with an integer (only arrays and functions).
Upvotes: 1
Reputation: 1340
With the line below you're passing the address of a to the display function. This will not work because display(int b)
is expecting a parameter of type int
.
display(&a); // should be replaced by display(a)
If you want to print the value of a
in the display function by sending its address you should do the following:
main()
{
int a=7;
display(&a); //Pass the address of variable a
}
display(int *b) //Is expecting an address as argument
{
printf("%d ", *b); //Print the value at that address
}
Upvotes: 1