在 C 中初始化指向常量对象的常量指针

托文

是否可以创建指向常量浮点数的常量指针?我正在这样做,但在这种情况下,温度不是恒定的。

float* temp = malloc(sizeof(float));
*temp = 22.5;
const float *const border = temp;

我很清楚这种情况在任何现实生活中都不可行。

阿查尔

首先float* temp = malloc(sizeof(float));应该是

float* temp = malloc(sizeof(*temp)); /* it works for any data type */

其次,是否可以创建一个指向常量浮点数的常量指针?是的,它可能。

int main() {

        float *temp = (const float*)malloc(sizeof(*temp));
        *temp = 22.5;
        const float *const border = temp; /* value & address both constant */

        /* now you can modify border and temp */
        #if 0
        *border = 10.5; /* not possible, cant change value*/
        border+=1;/* not possible, can't change address */
        #endif

        /* once done , free() it */
        free(temp);
        return 0;
}

但在上面的例子中*temp = 10.5是可能的,因为*temp不是constant

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章