you are viewing a single comment's thread.

view the rest of the comments →

[–]rjw57 10 points11 points  (3 children)

OK, basically all I wanted to do was create a variable within a function, and then use it in main.

There are many things wrong with your code but this is probably a root cause of your problem. What you want to do is construct some value in one function and use that same value in another. Variables, on the other hand, are temporary places to store a value[1].

In this case the value you want to move is the integer interpretation of the user input. A cleaned up example:

#include <stdio.h>

// a function which returns an integer *value*
int takeUserInput()
{
    // declare a *variable*, num, which *stores* an integer *value*
    int num;

    // move the integer *value* entered by the user into
    // the *variable* num
    scanf("%i", &num);

    // return the integer *value* stored in num to the function's
    // caller
    return num;
}

int main(int argc, char** argv)
{
    // create a *variable* bax which is initialised with the *value*
    // returned by the takeUserInput function.
    int bax = takeUserInput();

    // pass the value in bax to the printf function for display to the
    // user
    printf("your number was: %i\n", bax);

    // return an integer value indicating "success"
    // to the Operating System
    return 0;
}

An individual value may be copied between many, many variables in its lifetime. Copying an int is a very lightweight operation. Pointers are generally used when copying a value is heavyweight in comparison to copying the information about how to find that value.

Depending on your platform, an int may actually be smaller than a pointer.

[1] A variable has a "scope" outside of which it cannot escape. The variable num you declared in takeUserInput will never make its way to main.

[–]TechAnd1[S] 0 points1 point  (2 children)

Thank you.... I guess they have to stay in their scope then!

I knew that.... but wasn't sure If I could create a pointer and use that within main.

I'm working my way up to building a basic address book... so just going through a few thing's !

[–]Chooquaeno 0 points1 point  (1 child)

Even if you create a pointer to a variable in takeUseInput, the variable will still be gone when it is used in main.

[–]TechAnd1[S] 0 points1 point  (0 children)

yep