question

NoahL-4581 avatar image
0 Votes"
NoahL-4581 asked NoahL-4581 commented

Parameter & * diff

131170-%E1%84%83%E1%85%AE%E1%86%AF%E1%84%8B%E1%85%B4-%E1%84%8E%E1%85%A1%E1%84%8B%E1%85%B5.png



void f1(int& a) {
a = 1;
}

void f2(int* a) {
*a = 2;
}

void main() {
int x = 0;
f1(x);
std::cout << x << std::endl;

 f2(&x);
 std::cout << x << std::endl;

}


f1, f2가 결국 main함수의 x 데이터를 바꾸는 같은 동작을 하는데,

실제 둘의 차이는 뭘까요?

c++
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Translation: f1 and f2 end up changing the x data of the main function, doing the same thing, What's the real difference between the two?

For the simple case of a scalar such as int, the only practical difference is the need for the dereference operator (*) in f2.

If the argument is an array, using sizeof(a) in f1 would evaluate to the actual array size while in f2 it would evaluate to the size of a pointer. Even using sizeof(*a) in f2 will not return the array size.

If the argument is a class or struct, f1 must use the . operator to access a member while f2 must use the -> operator.

1 Vote 1 ·
NoahL-4581 avatar image NoahL-4581 BarrySchwarz-8780 ·

Thank you so much

0 Votes 0 ·

1 Answer

DavidLowndes-6766 avatar image
0 Votes"
DavidLowndes-6766 answered

I think you're looking to understand the difference between a reference and a pointer.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.