我想用 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/