如何形容常量指针在C / C ++的数组? [英] How describe const pointer to an array in C/C++?

查看:141
本文介绍了如何形容常量指针在C / C ++的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是指向一个 INT [10]类型(ptr-> INT [10]) INT(*变种)[10]
但如何描述那些类型的打击?

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

其类型为常量指针 INT [10] (常量PTR - > INT [10])

这是该类型常量指针 const int的[10](常量ptr-> const int的[10])


解决方案

  INT(* ptr1的)[10] =的malloc(sizeof的(INT)* 10); //指针为int [10]
const int的(* ptr2所)[10] = malloc的(的sizeof(int)的* 10); //指向const int的[10]
INT(* const的ptr3)[10] = malloc的(的sizeof(int)的* 10); //常量指针为int [10]
const int的(*常量ptr4)[10] = malloc的(的sizeof(int)的* 10); //常量指针const int的[10]* ptr1的[0] = 10; // 好。
* ptr2所[0] = 10; // 不好。
* ptr3 [0] = 10; // 好。
* ptr4 [0] = 10; // 不好。ptr1的=的realloc(ptr1的,的sizeof(INT)* 10); // 好。
PTR2 =的realloc(PTR2,sizeof的(INT)* 10); // 好。
ptr3 =的realloc(ptr3,sizeof的(INT)* 10); // 不好。
ptr4 =的realloc(ptr4,sizeof的(INT)* 10); // 不好。

I know the type which is pointer to an int[10] (ptr->int[10]) is int (*var)[10], but how to describe those of type blow?

the type which is pointer to the const int[10] (ptr->const int[10])

the type which is const pointer to the int[10] (const ptr->int[10])

the type which is const pointer to the const int[10] (const ptr->const int[10])

解决方案

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.

这篇关于如何形容常量指针在C / C ++的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆