c++ - 指针变量的地址

标签 c++ c

最近在学习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/

相关文章:

c++ - 事件驱动编程 : callback vs message polling

c - ld : 0711-317 error : Undefined symbol: . kget_proc_info

c++ - C程序检测物理链路状态和丢包

c - 如何重新排序字符数组中的位置

c - 如果在输入中找到小写字母,在使用C加密之前如何将其转换为大写?

c++ - 在 C++ 中实现类型列表

C++ 从二叉搜索树中删除节点

c++ - QTextStream 没有输出任何东西,我做错了什么?

c++ - setWindowFlags(Qt::WindowStaysOnTopHint) 隐藏 Qt 窗口

c - 我在编译 c 使用 mongodb c 驱动程序时遇到错误 "undefined reference to ` mongo_client'"