S Mahajan
S Mahajan

Reputation: 113

Reason for getting garbage value in C

I'm running this code and getting some garbage value while printing *ptr. What could be the possible reason and how can I avoid getting that?

# include <stdio.h>
int main()
{
  int test = 1; 
  int *ptr = &test;
  *ptr++ = 10; 
  test++; 
  printf("\nThe value is %d", *ptr);
}

Upvotes: 1

Views: 90

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 280

The statement *ptr++ increments the pointer which could not be valid for your program. Rewrite the statement as *ptr = 10;

Upvotes: 0

Zan Lynx
Zan Lynx

Reputation: 54325

You moved ptr with ptr++. Why?

Don't do that.

Upvotes: 4

Related Questions