最近在学习c语言,碰到这段代码。 ptr 已经是指针类型的变量,那么 &
运算符对它有什么影响,因为我知道通常运算符用来获取非指针变量的地址。
struct name {
int a; float b; char c[30];
};
int main()
{
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr = (struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
for(i=0; i<n; ++i) {
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f", &(ptr+i)->c, &(ptr+i)->a, &(ptr+i)->b);
}
}
最佳答案
&(ptr + i)->c
这获取存储在 ptr 的第 i 个元素处的变量 c 的地址。所以你的第一直觉是正确的。
ptr+i
只是指针算术运算以找到数组的第 i 个元素。
(ptr+i)->c
从该结构访问字段 c
,&
获取该变量的地址。
关于c++ - 指针变量的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19140657/