【问题标题】:How describe const pointer to an array in C/C++?如何在 C/C++ 中描述指向数组的 const 指针?
【发布时间】:2015-01-02 07:35:04
【问题描述】:

我知道指向int[10] (ptr->int[10]) 的类型是int (*var)[10], 但是如何描述那些类型的打击?

指向const int[10] (ptr->const int[10])的类型

类型是const 指向int[10] (const ptr->int[10])的指针

类型是const 指向const int[10] (const ptr->const int[10])的指针

【问题讨论】:

  • 使用 typedef。问题解决了。
  • 什么是类型打击?它是在某处定义的吗? :p
  • @thang 类型的打击是当您在模板代码中出错时,您会在 C++ 编译器错误中遇到这种情况。
  • 哦,好吧,那太棒了。

标签: c++ c arrays pointers syntax


【解决方案1】:
int (*ptr1)[10] = malloc(sizeof(int)*10);             // Pointer to int[10]
const int (*ptr2)[10] = malloc(sizeof(int)*10);       // Pointer to const int[10]
int (* const ptr3)[10] = malloc(sizeof(int)*10);      // const Pointer to int[10]
const int (* const ptr4)[10] = malloc(sizeof(int)*10);// const Pointer to const int[10]

*ptr1[0] = 10; // OK.
*ptr2[0] = 10; // Not OK.
*ptr3[0] = 10; // OK.
*ptr4[0] = 10; // Not OK.

ptr1 = realloc(ptr1, sizeof(int)*10); // OK.
ptr2 = realloc(ptr2, sizeof(int)*10); // OK.
ptr3 = realloc(ptr3, sizeof(int)*10); // Not OK.
ptr4 = realloc(ptr4, sizeof(int)*10); // Not OK.

【讨论】:

    【解决方案2】:

    像你一样声明变量:

    const int somevar[10];
    

    现在用新的类型名替换变量名,并在前面加上单词 typedef。

    typedef const int ci10_type[10];
    

    现在ci10_typeconst int [10] 的类型

    只要你知道如何声明它们,你也可以对更复杂的类型做类似的事情。 (函数和数据)

    typedef const int *cpi10_type[10];
    typedef const int (*pci10_type)[10];
    

    对于这些类型的指针,您可以使用:

    ci10_type *pci10var;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多