1

1.

int *a;
*a=5;
printf("%d",*a);

Why this one is not giving any output, end with returning big value?

2.

int *a,b=1;
a=&b;
*a=5;
printf("%d",*a);

Why this one works well and shows Output as 5?

1
  • 2
    "different ways to initializing pointer": Case 1 does not initialise the pointer a, whereas case 2 does: a=&b. Commented Apr 9, 2015 at 13:47

3 Answers 3

3

In first code snippet

int *a;

a is a pointer and is not pointing to any valid memory location and you dereference the pointer which will lead to undefined behavior.

The second code snippet is good and valid You have a pointer to a variable b and dereferecnce it.

a = &b; 
*a = 5;

Now the pointer is pointing to address of variable b and you change the contents at that location which is defined

Sign up to request clarification or add additional context in comments.

Comments

1

In first snippet, pointer a is not initialized and statement *a = 5; is writing 5 to an unallocated location. If the location modified by this statement belongs to the program, then it may behave erratically. If it belongs to the operating system the program will most likely crash. The behavior is undefined.

Comments

0

a is an int*, a pointer to int. In the first code snippet, where do you think a points to? The answer to that is a points to some random location. By using

*a=5;

you dereference the pointer and write 5 into the invalid memory location. This invokes Undefined Behavior and anything can happen. If you are lucky, you might end up having a Segmentation Fault.

In the second code snippet, b is an int, an integer variable. The memory for it is supplied by the OS on the stack. You make a point to the address of variable b. Then, dereferencing the pointer and writing 5 to that location is valid as the memory is allocated for variable b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.