Reputation: 55
I have a little confusion. Please look into following program:
#include<stdio.h>
void display (int *j, int *k);
int main()
{
int num1[]={1,2,3,4,5};
int num2[5];
int i;
display (num1,num2);
for (i=0;i<=4;i++)
printf("%d,", num2[i]);
return 0;
}
void display (int *j, int *k)
{
int l;
for (l=0;l<=4;l++)
{
k=j;
printf("%d,", *k);
j++;
k++;
}
}
In this printf("%d,", num2[i]);
is not giving the array. But it works when we put *k=*j;
in the function. Can you please explain why ? Thanks.
Upvotes: 0
Views: 129
Reputation: 42215
k=j
assigns the pointer k
to the value (address pointed to) of pointer j
. This toggles which array (num1
or num2
) k
points to but doesn't change the value of any array element.
*k=*j
sets the array element that k
points to to the value of the array element j
points to.
Upvotes: 1
Reputation: 13346
The statement k = j;
which means "assign the value stored in j
as the value of k
", merely copy the value stored in j
to k
. It does nothing on the arrays, just the pointer k
points to the address pointed to by j
. The assignment and increments effects only local variable j
and k
, nothing else.
When you write *k = *j;
, it essentially means "assign the content of address j
to address k
", which does the copying, and incrementing j
and k
points them to the next array element.
Upvotes: 0
Reputation: 13743
*k = *j
copies the content of the "cell" j
points to to the cell k
points to. On the contrary, k = j
makes k
point to where j
points. If you think about this, k = j
is wrong, as you do not alter the content of your arrays, but rather just change the local variable k
. Hence in your example, the print statement inside display
does, in fact, not print num2
, but num1
(as at the point of the print statement, k
points to the same location as j
does, which is an element of num1
).
Upvotes: 0
Reputation: 60037
Because you have not initialized the array num2
nor copy it from num1
.
Upvotes: 0