简体   繁体   中英

how does the c compiler find the address of a value when we are storing that in scanf in a variable?

In scanf("%d",&b); suppose we are storing 5 in b variable so address of 5 will be stored in b variable and not the value 5 but how does the compiler find the address of 5 and why we cant directly store the value 5?

That's not how it works. By using the "%d" format specifier, the scanf function assumes that the argument is a pointer to an int . So it get that pointer, uses the dereference operator, and stores the value 5 in the location pointed to by the pointer.

In essence what's happening is this:

int b;
int *pb = &b;  // Point to the variable b
*pb = 5;       // Dereference pointer and store value at that location

scanf takes the adress of a variable telling the program where to store your input. This means that your input eg 5 will be stored in the location your pointer (&b) points to. It does NOT store the adress of anything in the location pointed to by (&b).

Nope, you have misunderstood... All the parameters to functions pass information to the function. Scanf(3) is a function that stores the data specified by the %d format string into where? . Well, you specify that the data to be read is an integer expressed as an asscii string of digits into an integer variable, but how do you know where to store it? Because you pass to de function (from outside to the inside of the function) the address of an integer variable where you want to store the read integer .

The first thing to note is that you pass the address to the function, as a means to tell it where is the integer variable located. The function uses this address to fill the integer variable located there. So the function doesn't read an address, the function reads a number , and then it uses the address passed to know where to put that number.

The info in the parameter list always goes from outside to the inside of the function , and the results are passed out only in the result given by the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM