john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

passing pointers to functions

/* john pfeiffer 31aug07  explaining to myself passing by reference, again */
#include <stdio.h>

void function(int k, int** p, int* m)
{
    k++;
    printf("integer (copy) incremented %d\n",k);

    *m=*m+2;    /* we must dereference to affect the stored value */
    printf("integer reference incremented by 2 %d\n",m);

    m=m+2;   /* this is undefined behavior, are we modifying the address? */
    m=*m+2;  /* this is undefined behavior, are we modifying the address? */

    **p = **p + 1;  /* we are dereferencing the pointer to a pointer to get the int */
}

int main()
{
    int i=0;
    int* ptr;

    printf("integer value %d, integer address %d, pointer value %d\n",i,&i,ptr);

    ptr = &i;           /* the pointer now stores the value of the mem addr of i */
    printf("ptr = &i;\n");
    printf("integer value %d, integer address %d, pointer value %d\n",i,&i, ptr);

    printf("*ptr means the value held at the memory address stored by pointer %d\n",*ptr);

    printf("pass by value means a copy gets sent...\n");
    function(i,&ptr,&i);

    printf("integer after the function %d,\n",i);

    return 0;

}/* end of main */

  • « string to int conversions
  • commandline parameters pass arguments »

Published

Aug 31, 2007

Category

c

~145 words

Tags

  • c 95
  • functions 7
  • passing 1
  • pointers 2