Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
} 
like image 310
emge Avatar asked Apr 11 '26 01:04

emge


1 Answers

You can't - that's the whole point of const.

like image 106
Carl Norum Avatar answered Apr 12 '26 15:04

Carl Norum