繁体   English   中英

初始化指向 const 指针的指针

[英]Initialize pointer to const pointer

我想在 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

const int *,const int * const和int const *有什么区别?

在这种情况下,您必须使用memcpy 您不能通过const表达式进行赋值:

int *temp = &y->b;
memcpy((void *)&x->a, &temp, sizeof temp);

为了实现x->a++您可以执行以下操作:

int *temp;
memcpy(&temp, &x->a, sizeof temp);
++temp;
memcpy((void *)&x->a, &temp, sizeof temp);

您不能在初始化后将其分配给x->a ,因此您必须做一些愚蠢的事情,例如:

struct faa *y = (struct faa*)malloc(sizeof(struct faa));
struct foo tmp = {&y->b};
struct foo *x = (struct foo*)malloc(sizeof(struct foo));
memcpy(x, &tmp, sizeof *x); 

这是相同的情况:

  • 我锁上了门,扔掉了钥匙,因为在任何情况下,包括我在内的任何人都不得打开那扇门。
  • 这样做之后,我立即发现我无法打开门!
  • 我需要打开这扇门! 我怎么做? 我丢了钥匙。

您必须1)知道自己在做什么,2)不要做您实际上不想做的事情,包括不制定与程序的实际需求相矛盾的程序设计规范。

只需将声明更改为int const* a; 如果您打算更改该指针指向的位置。

为什么不打字。 以下代码将打印 6。

int main()
{
    int x = 5;
    const int* c{ &x};
    int* p{( int*) c};
    *p = 6;
    std::cout << x << std::endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM