我有一个变量,这是一个链接列表头。我想使它成为const,因为它永远不会被改变,整个程序都会使用这个变量,所以我认为我应该让它成为一个全局常量。问题是我在声明它为const后无法初始化它。如何初始化一个全局的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 head ptr的优点是什么?这就像是给一间草屋加一个铁门。 – 2010-06-24 18:47:06
@Amardeep:我认为这更像是用墨水写出某人的地址,而不是铅笔。不同的人可以进出,但房子总是在同一个地方(除非你住在肯塔基州)。 – 2010-06-24 19:46:46
@Amardeep @Tim Schaeffer - 是的Tim,我的目的是为了防止改变我的“头部”指针,以后无法释放内存,泄漏它......有没有更好的方法来做到这一点?或者就像......这么简单,如果它是“头”,就不要改变它。我有一个不同的名字,并意外地改变了它的另一个功能,直到我意识到我不想这样做。 – emge 2010-06-24 20:14:44