Search code examples
cpointersargumentsruntime-error

Please check the error in my code for increment of an integer


Here I have written a code for accepting an integer from user and increasing it by one globally using pointers.

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

int inc(int *a)
{
    *a=*a+1;
    return *a;
}

int main()
{
    int a;
    int *p;
    scanf("%d", &a);
    p=&a;
    printf("%d\n", inc(*p));
    printf("%d", a);
}

But when I run the program and enter a value for a, it terminates without giving any output. Please tell where I have erred and help to improve the code.


Solution

  • In this call of the function inc

    printf("%d\n", inc(*p));
    

    you are passing an object of the type int (*p) instead of a pointer as required by the function declaration

    You need to write

    printf("%d\n", inc(p));