[英]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
在这种情况下,您必须使用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.