c-指针地址混淆
发布时间:2022-06-21 11:40:10 273
相关标签:
我看到这样一段代码:
#include
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 之间有什么区别
在上面的代码中。当我有一个指向结构的指针并想要检索该结构的内部变量时,我总是会看到 peresonPtr->age 类型的代码。
所以说我有一个结构
struct A {
int x;
int y;
};
struct A f1;
struct A *f2 = &f1;
然后我知道我可以做到:
f2->x, f2->y 得到结构体 f1 中的 x, y 变量的 x 和 y 的值。但是 &f2->x, &f2->y 是什么意思?
或者 &personPtr->age 中 & 的使用与这里的 scanf 函数有关?(因为它在这里的 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;
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报