Mauricio De armas
Mauricio De armas

Reputation: 2289

How to get a int with scanf()

void pedir_diag(int* diag){
  scanf("%i", &diag);
}

int main() {
  int number;

  pedir_diag(&number);

  return 0;
}

When I compile introduce an integer and expect that number int variable in the main have the value introduced but is not set

I have this, in my code but i am not able to set diag variable with scanf() function.

Upvotes: 1

Views: 1718

Answers (2)

Swordfish
Swordfish

Reputation: 13134

diag is already a pointer so no need for the address-of operator (&) in the call to scanf():

void pedir_diag(int *diag)
{
    scanf("%d", diag);
}

But to do it that way is kinda stupid. You have no way to check for erroneous input.
Better:

#include <stdbool.h>

bool pedir_diag(int *diag)
{
    return scanf("%d", diag) == 1;  // *)
}

*) scanf() returns the number of successful conversions, so if the number of successful conversions is 1 we return true.

Usage:

#include <stdio.h>

int main(void)
{
    int foo;

    if (!pedir_diag(&foo)) {
        fputs("Input error :(\n\n", stderr);
    }
    else {
        // have fun with foo
    }
}

Upvotes: 7

The best way to use scanf through your entire coding life is by remembering the following rule

scanf("%[direction_of_what_to_scan][special format character]",
    Pointer_on_some_memory_location);

What scanf does is that it stores what the input was (with some length restrictions) to a memory address. So, either:

int n1;
scanf("%d",&n); //which means the address of variable n1 in memory

or

int *n2 = &n1;
scanf("%d",n) // &doesn't need to be used cause n2 is now already pointer to an integer

Both will are different implementations of the same thing, they differ to the part of using pointers,for which C is well-known,and even applicable these days.

Upvotes: 2

Related Questions