Reputation: 115
I am learning how to use pointers in C and I am having trouble with this little program. In main, I want to get the value in the parameter.
int testing(int *number) {
int num = 12;
number = #
return 0;
}
int main() {
int num;
testing(&num);
printf("The number is: %d", num);
return 0;
}
Essentially, I want to print the num pointer after it goes through the testing function. Therefore, I want num to be 12. Currently, when I print num, it is a random number. Any ideas? Thanks.
Upvotes: 0
Views: 1700
Reputation: 11
Instead of that, you should dereference the passed pointer to write the integer there:
*number = num;
Upvotes: 0
Reputation: 33
This is a fundamental issue in your code. If pass a function argument by reference you actually pass a copy of the address of your value to the function. Therefore changing the address inside a function like you do with the lines:
int num = 12;
number = #
does not have an impact in the caller scope (your main). You have to write the value at the position of the variable:
*number = num
In C it helps to think in addresses and where your values are stored. From an hardware point of view a function argument is placed in a register or on the stack and the CPU jumps to the location of your function. These values are not retrieved after the function terminates and the CPU jumps back.
Upvotes: 1
Reputation: 75062
number = #
is changing the local parameter (copy of what is passed). This means nothing because number
is not used after that.
Instead of that, you should dereference the passed pointer to write the integer there: *number = num;
Upvotes: 3