meatmeatof
Technical User
program 1
int main() {
int a = 2;
int b = 3;
swap (&a, &b); //extract the address of a and b
return 0;
}
void swap(int* a, int*b) {
*a = *a + 2; //dereference it and assign new value to a.
*b = *b + 2;
}
In program 1, we need to use *.
Program 2
/*This program adds two integers read from the keyboard and prints the results
written by : xxx
Date : xxx
*/
#include <stdio.h>
//Function Declaration
void getData(int* a, int* b);
int main(void){
//Local Declaration
int a;
int b;
getData(&a, &b);
printf("**Main:\t\ta = %d;\tb = %d\n", a, b);
system("PAUSE");
return 0;
}
/*---------------getData()----------------------------------------
This function reads two integers from the keyboard.
pre Parameters a and b are addersses, it stores address
post Data read into parameter address
------------------------------------------------------------------*/
void getData(int* a, int* b) {
printf("Please enter two integer number: ");
scanf("%d %d", a,b);
printf("**getData:\ta = %d;\tb = %d\n", *a, *b);
return;
}
Please enter two integer number: 333 22
**getData: a = 333; b = 22
**Main: a = 333; b = 22
In program 2, the scanf function didn't use any & or * on variable a and b. why?? how does scanf directly access a and b in the calling function? The textbook said if you want modify the content of a variable in calling function, you need to use their address.
This point confuse me. I don't understand why scanf didn't use any address point or dereference thing.
I am so lost.
int main() {
int a = 2;
int b = 3;
swap (&a, &b); //extract the address of a and b
return 0;
}
void swap(int* a, int*b) {
*a = *a + 2; //dereference it and assign new value to a.
*b = *b + 2;
}
In program 1, we need to use *.
Program 2
/*This program adds two integers read from the keyboard and prints the results
written by : xxx
Date : xxx
*/
#include <stdio.h>
//Function Declaration
void getData(int* a, int* b);
int main(void){
//Local Declaration
int a;
int b;
getData(&a, &b);
printf("**Main:\t\ta = %d;\tb = %d\n", a, b);
system("PAUSE");
return 0;
}
/*---------------getData()----------------------------------------
This function reads two integers from the keyboard.
pre Parameters a and b are addersses, it stores address
post Data read into parameter address
------------------------------------------------------------------*/
void getData(int* a, int* b) {
printf("Please enter two integer number: ");
scanf("%d %d", a,b);
printf("**getData:\ta = %d;\tb = %d\n", *a, *b);
return;
}
Please enter two integer number: 333 22
**getData: a = 333; b = 22
**Main: a = 333; b = 22
In program 2, the scanf function didn't use any & or * on variable a and b. why?? how does scanf directly access a and b in the calling function? The textbook said if you want modify the content of a variable in calling function, you need to use their address.
This point confuse me. I don't understand why scanf didn't use any address point or dereference thing.
I am so lost.