In the following code, why does the value of 'b' remain 16 instead of 18??

#include <stdio.h>
main( )
{
    int a[5], i, b = 16 ;
    for ( i = 0 ; i < 5 ; i++ )
    a[i] = 2 * i ;
    f ( a, b ) ;

    for ( i = 0 ; i < 5 ; i++ )
    printf ( " %d ", a[i] ) ;
    printf( "\n%d", b ) ;
}
f ( int *x, int y )
{
    int i ;
    for ( i = 0 ; i < 5 ; i++ )
    x[i] += 2 ;
    y = y + 2 ;
}

Because b is being passed a new instance rather than a reference pointer. You can fix that like this:

#include <stdio.h>
main( )
{
  int a[5], i, b = 16 ;
  for ( i = 0 ; i < 5 ; i++ )
    a[i] = 2 * i ;
  f ( a, &b ) ;

  for ( i = 0 ; i < 5 ; i++ )
    printf ( " %d ", a[i] ) ;
  printf( "\n%d", b ) ;
}

void f ( int *x, int *y )
{
  int i ;
  for ( i = 0 ; i < 5 ; i++ )
    x[i] += 2 ;
  *y = *y + 2 ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.