c - Using malloc with static pointers -


i know declaring ststic variable , initializing in waystatic int *st_ptr = malloc(sizeof(int)); generate compile error message(type initializer element not constant),and solving using separate statements in way static int *st_ptr; st_ptr = malloc(5*sizeof(int));


i need understand difference between initialization operator , assignment operator in case ?and why way solved problem ?

first, let's have brief on initialization vs. assignment.

  • initialization:

this used specify initial value of object. usually, means, @ time of defining variable, initialization takes place. value initialize object called initalizer. c11 , chapter 6.7.9,

an initializer specifies initial value stored in object.

  • assignment:

assignment assigning (or setting) value of variable, @ (valid) given point of time of execution. quoting standard, chapter 6.5.16,

an assignment operator stores value in object designated left operand.

in case of simple assignment (= operator),

in simple assignment (=), value of right operand converted type of assignment expression , replaces value stored in object designated left operand.


that said, think, query has initialization of static object.

for first case,

static int *st_ptr = malloc(sizeof(int));  

quoting c11 standard document, chapter §6.7.9, initialization, paragraph 4,

all expressions in initializer object has static or thread storage duration shall constant expressions or string literals.

and regarding constant expression, chapter 6.6 of same document, (emphasis mine)

constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when contained within subexpression not evaluated.

clearly, malloc(sizeof(int)); not constant expression, cannot use initialization of static object.

for second case,

static int *st_ptr; st_ptr = malloc(5*sizeof(int)); 

you not initializing static object. you're leaving uninialized. next instruction, you're assigning return value of malloc() it. compiler not produce complains.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -