Pointer confusion

Here are two programs that pass a pointer to a variable but behave differently. Shouldnt the i in second program be 0 after the function call?

#include<stdio.h>

void changeI(int *i)
{
 *i = 10;
}

int main(void)
{
 int i=5;
 printf("%d before\n", i);
 changeI(&i);
 printf("%d after\n", i);
 return 0;
}
chlsvnc01> ./temp
5 before
10 after
chlsvnc01> cat prttst3.c
#include<stdio.h>

void copy_array(int * destArray, int * srcArray, int *i)
{
 while(*i)
 {
  *destArray++ = *srcArray++;
  *i--;
 }
 printf("%d is after copy\n", *i);
 return ;
}

int main (void)
{
 int i=30;
 int s[30] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
 int d[30];

 printf("i before = %d\n",i);
 copy_array(d,s,&i);
 printf("i after = %d\n",i);

 for(i=0;i<30;i++)
  printf("%d\t",d);
 printf("\n");
 return 0;
}
chlsvnc01> ./prttst3
i before = 30
0 is after copy
i after = 30
0       1       2       3       4       5       6       7       8       9       10      11      12      13      14      15      16      17      18      19      20      21      22      23      24      25      26      27      28      29

The problem is that:

*i--;

decrements the pointer, not the pointed-to value. I.e. it's equivalent to:

*(i--);

What you really want is:

(*i)--;

(On my machine at least, your program worked by accident simply because of the location of i and s on the stack.)

1 Like