I found the following code in my textbook:
#include<stdio.h>
void disp( int *k)
{
printf("%d",*k);
}
int main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ;
return 0;
}
}
The code works just fine, but I have doubts regarding the logic:
-
I am sending the address of variables of the array. But in the
dispfunction I am using a pointer variable as the argument and printing the value of the pointer. So the type of argument sent from themainfunction should mismatch with the argument ofdisp. So how does it work? -
I tried to do the same by changing the
dispfunction asvoid disp( int (&k)) { printf("%d",*k); }but I am getting an error. What should I do to make it work by taking an address as an argument, i.e.
void disp(int &k)?
When you do: –
The above statement is broken into: –
So, basically,
kis the anintegerpointer, that points to the address of the current element in yourarray.So, when you print
*k, it is equivalent to: –*(&marks[i]), which dereferences the value and prints the elementmarks[i].So, in the below code, you can understand, how the whole process of
pointerassignment andde-referencingtakes place: –Also, since you cannot declare variable like: –
You cannot have them as parameter in your function: –
Because, eventually the address of
array elementpassed is stored in this variable. So, it has to beint *k.