emge emge - 2 months ago 6
C Question

how to initialize a global const pointer?

I have a variable which is the head to a linked list. I want to make it const because it should never be changed, the variable is used throughout the program, so I thought I should make it a global const. The problem is that I couldn't initialize it after I declared it const.

How can I get around this problem?

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;
}

Answer

Remove the const qualifier from the global declaration and declare rest_of_code as a function that takes the const-qualified version of the pointer.

//globals
POINT * mypoint_head;

void rest_of_code(POINT* const mypoint_head)
{
    mypoint_head = NULL;    // this errors out now
}
int main(int argc, char *argv[])
{
    int size = 100;
    mypoint_head= InitPoint(size);   // no longer errors out
    //rest of code
    rest_of_code(mypoint_head);
}