Reputation: 19
#include <stdio.h>
int main()
{
int N = 4;
int *ptr1;
// Pointer stores
// the address of N
ptr1 = &N;
printf("Value @Pointer ptr1 before Increment: ");
printf("%d \n", *ptr1);
// Incrementing pointer ptr1;
ptr1++;
*ptr1=5;
printf("Value @Pointer ptr1 after Increment: ");
printf("%d \n\n", *ptr1);
return 0;
}
The output I was expecting is that printf prints the value 4
and then the value 5
.
But after executing the 1st printf statement the code exited and the code never printed the 2nd printf.
Can anyone please explain what am I doing wrong?
As per my knowledge I am incrementing a pointer then storing a new value into the incremented address.
Have I understood it right?
Upvotes: 0
Views: 130
Reputation: 73
When you try to increment a pointer, what c does is this: "ptr + 1 * sizeof(int)" (assuming that ptr is an int pointer). So, now, it is pointing 4 bytes ahead of the variable "N"(assuming that you are on a 64 bit machine) which probably is occupied by another program. When you dereference it you are taking the value that is stored 4 bytes ahead of "N". With that being said, I recommend this:
(*ptr)++
Upvotes: 0
Reputation: 48042
You're incrementing the pointer.
But it looks like you want to increment the value that the pointer points to.
Try this:
(*ptr1)++;
The parentheses are important: they say that what you're incrementing is the contents of the pointer pointed to --
that is, what the ++
operator is applied to is the subexpression (*ptr1)
.
See also Question 4.3 in the C FAQ list.
Upvotes: 1
Reputation: 2180
Welcome to stackoverflow :D
The problem is that you have allocated space for a single integer. But you're trying to access two integers. Which is undefined behavior; meaning that sometimes it will crash, like in your case, and sometimes it might work, and some other times it might work but give unpredictable results.
When you increment the pointer you go to an address in memory that you have not allocated. If you want two integers, maybe allocate an array like this:
int N[2] = {4, 4};
Now when you increment the address of the pointer, you're reaching valid memory that you have allocated.
Upvotes: 1