Chris Barry
Chris Barry

Reputation: 4594

Pointer changes value for no reason c++

I am trying to store a pointer as a member variable, so that during the life of the class, other functions can work with the pointer.

However, when I first setup this class, the pointer variable is correct for the first printf, but when the second one is called, the value is 0x0

In my main, setup is called once first, and then update is called repeatedly.

member variables are declared in the h file.

why does the pointer change between the first and second printf?

//Main//

int Main(){

TestClass testclass;

unsigned char array[1000];
unsigned char * pVideoIn = array;

testclass.setup(pVideoIn);

for (int i =0; i < 100; i++)
    {
    testclass.update();
    }
}

//header//

#ifndef _TEST_CLASS
#define _TEST_CLASS

class TestClass {

public:
void setup(unsigned char* videoIn); 
void update();

unsigned char* videoInp;
unsigned char* videoOutp;

int noPixels; 
};

#endif

//class//

#include "TestClass.h"

void TestClass::setup(unsigned char* videoIn)
{
videoInp = videoIn;
videoOutp = videoOut;
noPixels = pixels;

printf("in class app = %p \n", videoInp);

}

void TestClass::update()
{ 
printf("in class app = %p \n", videoInp); 
}

Upvotes: 1

Views: 4442

Answers (2)

jfabrix
jfabrix

Reputation: 66

I know this one is a bit old, and it's impossible to to provide a solution for this specific problem, since it cannot be recreated with the code provided, but I recently bumped into something similar, and thought I'd share some rather general tips regarding how to go about solving this.

Basically: be careful with arrays. I forgot about this as programming for Java and C# made me a bit lazy: you don't get an IndexOutOfBoundsException in c++, the program just goes to whatever memory location you tell it to, and modifies it accordingly. If you're lucky, you'll get an Access Violation error then and there, as the program attempts to write to a location that is outside of what the OS has allocated for it. If you're not lucky, it will modify a part of the memory that belongs to it, messing up whatever pointers, variables or objects you've declared.

Upvotes: 3

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

As written, and after fixing minor compilation errors (by supplying NULL and 0 as the other arguments to setup, for example), the code as presented does not exhibit the behaviour you describe when I run it. In particular, it prints out the same non-NULL pointer 101 times. Conclusion: this is not the code you're having trouble with (you need to post an example that actually exhibits the problem).

Upvotes: 3

Related Questions