0

I'm trying to make a program that has a function that gets an int and using pointers increases the int by 1.

This is what i was trying to do but it doesn't work...

#include <stdio.h>
#include <stdlib.h>

void inc(int x);

int main()
{
    int x = 0;

    printf("Please enter a number : ");
    scanf("%d", &x);

    printf("The value of 'x' before the function is - '%d'\n", x);
    inc(x);
    printf("The value of 'x' after the function is - '%d'\n", x);

    system("PAUSE");
    return 0;
}

void inc(int x)
{
    int* px = &x;
    *px = x + 1;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
Ofek Ezon
  • 29
  • 1
  • 5
  • C11 draft standard, `6.5.2.2 Function calls, Section 4 An argument may be an expression of any complete object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument. 93)A function may change the values of its parameters, but these changes cannot affect the values of the arguments.[...]` – EOF Mar 15 '16 at 21:20
  • You need to pass the param to inc using a pointer. http://www.tutorialspoint.com/cprogramming/c_passing_pointers_to_functions.htm – marcadian Mar 15 '16 at 21:20
  • Notice how you pass that `x` by-address to `scanf` to read the value and have it stored in *your* variable back here in `main()` ? Yeah, gonna need to do that with your own function (which has to change to take a pointer parameter). – WhozCraig Mar 15 '16 at 21:23

1 Answers1

1

Your existing code passes a copy of the value to the function, and this copy is incremented, so the original is unchanged.

Instead, you must pass the pointer and reassign to the location the pointer points at.

#include <stdio.h>
#include <stdlib.h>

void inc(int *x);

int main()
{
    int x = 0;

    printf("Please enter a number : ");
    scanf("%d", &x);

    printf("The value of 'x' before the function is - '%d'\n", x);
    inc(&x);
    printf("The value of 'x' after the function is - '%d'\n", x);

    return 0;
}

void inc(int *x)
{
    *x = *x+1;
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329