다음의 코드의 결과를 알아맞춰야 하는 문제이다.

구조체와 포인터의 이해가 필요한 문제이다

답:  6

 

답이 6으로 나오게 된 이유를 처음에는 다음과 같이 생각했다 (조금 틀린 생각이니 너무 자세히는 보지 말자).

(영어로 되어 있는 이유는 stackoverflow에 올리기 위해서 적은 부분이니, 이 부분은 감안해서 보면 된다.)

 

1. Due to struct node, num 3, 5, 6 are set into a, b, c in the num variable.

   (struct node에 의해 num 3, 5, 6은 각각 a, b, c에 할당된다)

2. *ptr points the start address of num due to struct node *ptr = # which means that it points to the address of the index = 0 which is 3 in {3, 5, 6}.

   (*ptr는 num의 시작주소를 가리키기 때문에 0번 index를 가르키므로 *(int)ptr 은 3을 출력할 것이다.)

3. Therefore,  printf("%d\n", *ptr); prints 3,

   (따라서, 만약 printf("%d\n", *ptr);가 있다면, 3이 출력이 될 것이고)

4. printf("%d\n", *((int*)ptr + 1 + (3-2))); is printing *(0+1+1) which is index = 2 of num which equals to 6.

   (printf("%d\n", *((int*)ptr + 1 + (3-2)));는 결국 *(0 + 1 + 1)이 되므로 2번 index인 6이 출력된다.)


이걸 이제 제대로 구조체를 사용해서 설명해야한다. 위의 index는 array(배열)에 사용하는 것이므로, 틀리기 때문에, 다음과 같이 설명해야 제대로 된 설명이라고 할 수 있다.

(다음 답변은 stackoverflow의 친절한 어느 답변자가 내 생각을 더 정확히 바꿔 설명해준 것이다)

1. Due to the initializer, 3, 5, 6 are set into a, b, c in the num variable.

   (3, 5, 6은 초기화되어 a, b, c의 num 변수에 할당된다)

2. *ptr points to the start address of num due to struct node *ptr = #, which is the same as the address of num.a.

   (*ptr = #에 의해 *ptr는 num의 시작주소를 가르키고, 이는 num.a의 주소와 똑같다.)

3. Therefore, printf("%d\n", *ptr); prints 3.

   (따라서, printf("%d\n", *ptr);가 있다면, 3이 출력된다)

4. (int*)ptr yields a pointer to num.a with the proper type.

   ((int*)ptr는 num.a를 int*로 type casting을 한다.)

5. Adding 2 to ptr means that we add the size of two ints to the address. Note that the typecast is very important, as we would've otherwise added the size of two struct nodes to the address; the effect of adding to a pointer depends on the pointer type.

   (ptr+2는 주소에 int size를 2개 더한다는 뜻이다. 참고로, typecast는 굉장히 중요하다. 그렇지 않았다면 struct node의 주소size 2개를 따로 더했어야 할 것이다)

6. The resulting address is the same as the address of num.c. At that address, we find the integer value of 6.

   (결과값의 주소는 결국 num.c의 주소와 같다. 따라서 결과값은 6이 되는 것이다.)

 

참고로, 구조체의 경우 메모리상 주소지는 연속할당 된다는 특성 때문에 주소이동이 가능한 것이다.

 

문제출처: https://www.sololearn.com/
설명출처: https://stackoverflow.com/questions/63543259/how-the-struct-and-pointer-acts/63543401#63543401

다음의 코드의 결과를 알아맞춰야 하는 문제이다.

답: SoloLearn SoloLearn (배경을 다르게 해보아라.. 보일 것이다)

 

 

틀린 이유는 내가 제대로 함수포인터를 아직 이해하지 못했기 때문이다.

흔히 생각하는 () 연산자를 통해 함수를 호출하는 것을 생각하여 위의 코드에서 

void(*bar)() = foo;

에서

foo() 가 되어야 하는 줄 알았다.

 

이 참에 공부를 좀 해보자.

 

함수포인터(function pointer)란 함수의 주소를 저장하는 변수다.

https://dojang.io/mod/page/view.php?id=592 (코딩도장)에서 아주 깔끔하게 정리되어 있다 

 

따라서, bar에 foo함수를 할당한다. 다음과 같이 말이다.

 

(*bar)(); 이나 bar();이나 같은 표현이기 때문에 foo()는 2번 수행이 된다.

 

문제출처: https://www.sololearn.com/ 中

http://sololearn.com

 

SoloLearn: Learn to Code

Join Now to learn the basics or advance your existing skills

www.sololearn.com

이 사이트를 통해서 틈틈히 공부하면서 퀴즈를 푸는 재미도 있다.

 

퀴즈의 경우 이 어플을 사용하는 모든 사용자들을 상대로 할 수 있다.

 

퀴즈 뿐 아니라, 언어에 대해서 간단히 공부를 할 수 있기에 추천하는 어플이다.

 

앞으로는 퀴즈를 풀면서 틀리는 부분도 조금씩 정리해서 기록을 남길 생각이다.

+ Recent posts