gpt4 book ai didi

c - 如何初始化全局常量指针?

转载 作者:行者123 更新时间:2023-12-02 06:24:30 25 4
gpt4 key购买 nike

我有一个变量,它是链表的头部。我想让它成为常量,因为它永远不应该被改变,变量在整个程序中使用,所以我想我应该把它变成一个全局常量。问题是在我声明它为 const 之后我无法初始化它。

我该如何解决这个问题?

typedef struct PT {
int x;
int y;
struct PT *next;
} POINT;

//globals
POINT * const mypoint_head;

int main(int argc, char *argv[])
{
int size = 100;
mypoint_head= InitPoint(size); // error C2166: l-value specifies const object
//rest of code

}


POINT* InitPoint(int size)
{
POINT *tmp;
POINT *orig;
int a = 10;
int b = 1000;
orig = (POINT*) malloc (sizeof(POINT) * size);
if(orig == NULL)
return NULL;

tmp = orig;
for (i = 0; i < size; i++)
{
tmp->x = a++;
tmp->y = b++;
if (i == size -1) {
tmp->next = NULL:
}
else {
tmp->next = tmp+1;
}
tmp++;
}
return orig;
}

最佳答案

你不能——这就是 const 的全部意义所在。

关于c - 如何初始化全局常量指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3112915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com