c - 将指针初始化为 const 指针

标签 c pointers dynamic struct

我想用 C 语言做什么?

#include <stdio.h>
#include <stdlib.h>

struct foo{
    int const * const a;    // constPtrToConst is a constant (pointer)
                            // as is *constPtrToConst (value)
};

struct faa{
    int b;
};

int main(void){
    struct foo *x = (struct foo*)malloc(sizeof(struct foo));
    struct faa *y = (struct faa*)malloc(sizeof(struct faa));

    x->a = &(y->b);     // error: assignment of read-only member ‘a’ [that's ok] 
                        // (I)
    x->a++;    // It should not do this either...

    printf("%d,\t%p\n", *(x->a), x->a);    // (II)
    free(x);
    free(y);
}

我怎样才能初始化(I),我能得到这个(II)吗?

抱歉,没有分配是用那个指针初始化的。

这就是我想要动态获得的。

#include <stdio.h>

struct foo{
    int const * const a;
};

int main(void){
    int b = 5;
    struct foo x = {
        .a = &b
    };
    printf("%d\n", *(x.a));
}

我就是这样解决的。

不知道是不是最好的选择。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct foo{
    int const * const a;
};

struct foo* newfoo(int *var){
    struct foo *tempD = malloc(sizeof(struct foo));
    struct foo tempS ={
        .a = var
    };
    memcpy(tempD, &tempS, sizeof(struct foo));

    return tempD;
}

int main(void){
    int b = 5;

    struct foo *z = newfoo(&b);

    printf("%d,\t%p\n", *(z->a), z->a);
    // this is equivalent to printf("%d,\t%p\n", b, &b);

    free(z);
}

最佳答案

int const * const a; 是一种变量类型,常量 表示它不能更改(第二个 const),而第一个 const 表示它指向常量数据。

将结构更改为:

struct foo{
    const int* a;
};

现在你可以给a赋值,但是你不能修改a指向的值。

struct foo myFoo;
myFoo.a = (int *)5; //a points to location 5 now, valid
*myFoo.a = 4;       //Try to modify where a points = invalid and error

What is the difference between const int*, const int * const, and int const *?

关于c - 将指针初始化为 const 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44587882/

相关文章:

c++ - 这是类型转换吗?这是什么?

由函数修改的字符指针将无法正确显示更新字符串值

css - 动态高度不适用于绝对位置

php - 哪个更快,纯 HTML 还是来自数据库的存储 HTML?

c - Xmega 只有两个 IO 端口中断(INT0 和 INT1)

c - 什么是适合与 LPC1788 微 Controller 一起使用的 RTOS?

c - C 程序中的答案不正确,我缺少什么?

c - Windows下动态加载库的地址范围

arrays - 大小 n 的最大总和

C++ 字符串变成指针