Getting Error When Declaring and Assigning Pointer...


2 replies [Last post]
Vrutin
Vrutin's picture
Offline
Joined: 2011-10-07
Points: 0

#include <iostream>

#include <stdio.h>

#include <string.h>

 

using namespace std;

 

int main()

{

int *n;

*n = 20;

 

return 0;

}

 

Error is: Run-Time Check Failure #3 - The variable 'n' is being used without being initialized.

 

Using Visual Studio 2010

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
LoveCats
LoveCats's picture
Offline
W007! I watched 10 vids!
Joined: 2011-06-25
Points: 10

You pretty much mixed C & C++. iostream and namespace std are actually components of C++. Despite, that works fine for me. Tried with GCC (after removing C++ components) as well as VC++ 2010.

Its possibly misconfiguration in your complier. The code is working.

A_S
A_S's picture
Offline
A Coding BeautyW007! I watched 10 vids!
Joined: 2011-10-30
Points: 110

Besides using the C++ components, you probably should change your use of pointers. 

When you first declare the pointer it points to some random spot in memory, that something else could be using. Then when you asign that memory location the value of 20 it will overwrite the previous value. Because the memory wasn't "yours" to begin with, it could mess things up, even if it looks like there were no compilation errors. 

Instead use one of these options:

int *n = (int*)malloc(sizeof(int)); //here you allocate memory to store an interger in and you have your pointer point to it.

*n = 20; //now you can use the pointer to access and change to value stored at that spot in memory

or

int a = 7; //when you declare a normal variable memory gets allocated automatically

int *n = &a; //you can now create a pointer that points to the same spot in memory

*n = 20; //and you can change the value stored there

 

-sorry if this wasn't the clearest explanation, but if you really want to learn all this you should just watch the videos on pointers and

dynamic memory management