이런 코드가 있는데요.
#include<stdio.h>
struct person{
int age;
float weight;
};
int main(){
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age); // why use &personPtr->age, shouldn't it just be personPtr->age since personPtr is itself a pointer.
printf("Enter weight: ");
scanf("%f", &personPtr->weight); // similarly here: should it be personPtr->weight instead. Why the & in front of personPtr, I thought & means address, so wouldn't it means address of the pointer which seems wrong here if we want to show the weight value.
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
// however if I do: printf("weight: %f", &personPtr->weight); this doesn't print the value of weight. So it has to do with the scanf function?
return 0;
}
제가 이해할 수 없는 것은 &personPtr->age와 personPtr->age 사이의 차이점이 무엇일까 해서요.
struct에 대한 포인터가 있고 해당 struct의 내부 변수를 검색하려고 할 때 항상 peresonPtr->age 유형의 코드를 봅니다.
그러니 struct을 가지고 있다고 한다면
struct A {
int x;
int y;
};
struct A f1;
struct A *f2 = &f1;
여기서 이렇게 된다는 건 압니다.
struct f1 내에 있는 x, y 변수의 값 및 x, y 값을 구하려면 f2->x, f2->y를 쓰면 되는데 &f2->x, &f2->y는 무엇일까요?
또는 &in &personPtr->age의 사용은 여기서의 scanf 기능과 관련이 있습니까? (왜냐하면 scanf 함수의 사용 & inside는 여기서의 scanf 함수이기 때문입니다.)
누군가 차이점을 설명하고 왜 personPtr->age 대신 &personPtr->age를 사용하는지 설명해 주시겠습니까?
예를 들어 Mutex 함수의 다른 예에서는 &이 다시 표시됩니다.
uthread_mutex_t uthread_mutex_create () {
uthread_mutex_t mutex = malloc (sizeof (struct uthread_mutex));
mutex->holder = 0;
mutex->reader_count = 0;
spinlock_create (&mutex->spinlock); \\ why &mutex, instead of just mutex?????
uthread_initqueue (&mutex->waiter_queue);
uthread_initqueue (&mutex->reader_waiter_queue);
return mutex;
}
personPtr은 전체 개체 person1에 대한 포인터입니다.
personPtr = &person1;
따라서 이 식 personPtr->age는 개체 person1에 대한 포인터를 통해 참조를 통해 스캔에 전달해야 하는 데이터 멤버 age를 산출합니다.
scanf("%d", &personPtr->age);
보다 명확하게 하기 위해 다음과 같은 표현을 다시 쓸 수 있습니다.
scanf("%d", &( personPtr->age ));
© 2022 pinfo. All rights reserved.