Hello,
This is very silly question as millions discussions on call-by-value vs call-by-reference for programming beginners, but I need to confirm my understanding.
#include<stdio.h>
void swap(int *p, int *q) //Line 3
{
int tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
int main()
{
int i = 3, j = 5;
int *iptr, *jptr;
iptr = &i;
jptr = &j;
printf("Before swap: i = %d, j = %d\n", i, j);
swap(iptr, jptr); //Line 19
printf("After swap: i = %d, j = %d\n", i, j);
return 0;
}
I know swap(*iptr, *jptr) is wrong when I tried it,
$ gcc -o pg252b pg252_call-by_ref01b.c
pg252_call-by_ref01b.c: In function �main�:
pg252_call-by_ref01b.c:19:5: warning: passing argument 1 of �swap� makes pointer from integer without a cast [enabled by default]
pg252_call-by_ref01b.c:3:6: note: expected �int *� but argument is of type �int�
pg252_call-by_ref01b.c:19:5: warning: passing argument 2 of �swap� makes pointer from integer without a cast [enabled by default]
pg252_call-by_ref01b.c:3:6: note: expected �int *� but argument is of type �int�
My question is, as the function prototype at Line 3 is swap(int *i, int *j), in which the two arguments are pointers, whereas Line 19 passes two pointer addresses, which are "NOT" matching. Initially I tend to use swap(*iptr, *jptr) instead of swap (iptr, jptr), but not working. I did not see people ask why the function call uses addresses but the prototype declares with pointers. This gave me confusion. Could you guys explain it along with the warning message? Thanks a lot!