Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to give value to an incremented pointer.
So I have this following code:

C++
#include<iostream>
using namespace std;

int main()
{
	int *ptr,number1=1;
	ptr=&number1;
	ptr++;
	*ptr=3;
	cout<<*ptr;
}



What I have tried:

I expect the result to be 3 but instead the program stops working and terminates. What is wrong with my code.
Posted
Updated 15-Aug-16 18:54pm
Comments
Philippe Mori 17-Aug-16 11:08am    
This code has undefined behavior. Essentially, you should not dereference a pointer that do not point to allocated memory. So for your code to works number1 would need to be an array of at least 2 elements (since you increment the pointer once).

1 solution

You look confused with pointers.
To learn C/C++ basics read this book
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]
The C Programming Language - Wikipedia, the free encyclopedia[^]

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900