Constant Value assignment to Integer Pointer in C works for this case

First of all, both the snippets cause undefined behavior because of the dereference of uninitialized pointer i.

In your first case, you’re trying to dereference an uninitialized pointer i, so that is undefined behavior.

You’re doing

 *i = 100;

but think, where does i point to? Probably to some memory location which is not accessible from the process, so it is invalid memory access. This triggers the UB.

Same in the second snippet, too.

However, if you remove the usage of i from the second snippet, it will be OK.

After the proposed change, in the second snippet, you’re storing the starting address of the string literal into the pointer variable, i.e, assigning it. So, it is perfectly OK.

For a statement like

  str = "Hello";

you’re not defererencing str here, rather, assigning a pointer value to str, which is perfectly fine.


That said,

  • according to the C standard, for a hosted environment, void main() is not a conforming signature, you must use int main(void), at least.
  • A statement like printf("%u\n",i); also invokes undefined behaviour in it’s own way. In case you want to print the pointer, you must use the %p format specifier and cast the argument to void*.

Leave a Comment