0

i am trying to write an easier version of scanf. i want to basically be able for a pointer to be assigned whatever was scanned on user input like this:

int *p = (int) w_insc();

so here is my implementation:

void *w_insc()
{
    void *temp = 0;
    scanf("???", &temp);
    return &temp;
}

i am confused as what to assign the format parameter in scanf to. i also think returning an address of a variable that will soon be destroyed is not right so i thought of doing this:

int *p = 0;
p = (int) w_insc((int) p);

can someone help

user1169094
  • 157
  • 1
  • 1
  • 5

1 Answers1

0

You are right that returning a pointer to a soon-to-be-destroyed variable is not correct. You can solve this problem by returning a pointer to a memory region allocated with malloc (although the caller must remember to free this memory), or by taking a pointer as the argument to w_insc, and then filling in the pointer with the returned value.

However, there are much broader issues with trying to implement the w_insc function. There is no way for w_insc to know what the caller expects. Just because the caller casts the return value of w_insc to int doesn't allow w_insc to know that it should return an int. The only information that a C function has available to it is its set of parameters, plus any global variables in the program (and global variables are usually the wrong way to solve your problem). Note that a C function has no way of knowing what the caller will do with its return value. As a result, there is no way to write w_insc to take no parameters and return something scanned correctly based on some cast that the caller makes.

You could add a parameter to w_insc, making the declaration into

int w_insc(const char *format, ...)

This allows the caller to pass in a format string and a series of arguments detailing what they expect to get out of standard input. However, with this implementation you have just wrapped scanf with ... another function that looks just like scanf.

My advice: use the standard library functions, since they are standardized, and someone reading your code will know instantly what it means, rather than having to read through the definition of a nearly-trivial wrapper like the w_insc you have described.

Community
  • 1
  • 1
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52