0

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 ;
}

Edited by Narue: Added code tags

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by N1GHTS
0

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 ;
}

Edited by N1GHTS: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.