Help in function with pointers

Asked

Viewed 49 times

-1

Can anyone help me with this code ? not working, can’t find the error.

#include <stdio.h>

int chamar(int *n){

        printf("Digite o valor de n:");
        scanf("%d",&n);
        printf("%d",n);
        return 0;

        }

int main(void){

        int n;
        chamar(n);
        printf("\n%d\n",n);

        }

1 answer

1

To insert the value into the variable n within the main, you need to pass her memory address, and you do it just like in scanf:

chamar(&n);

and in the call method, as the parameter is already a pointer, you do not need to pass its memory address, thus getting:

int chamar(int *n){
    printf("Digite o valor de n:");
    scanf("%d",n);
    printf("%d",*n);

    return 0;
}

It is understood that the n of printf inside of chamar has a *, the * serves to create a pointer and to pick up the value from within the pointer, and the & serves to take the memory address of the variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.