Corey Was Here

I've created a class containing a System:: String^ variable, but everytime I try to set it equal to a value I get a Null execption error. I was just wondering if someone could tell me how I allocate the space to set it equal to another String^ value. Any help would be appreciated. Thanks.

Re: Visual C++ Language How do I allocate memory for a String^?

einaros

Use the gcnew operator: String^ myString = gcnew String("Hi there");




Re: Visual C++ Language How do I allocate memory for a String^?

Corey Was Here

Yeah Ive tried that, but I just get this error.

An unhandled exception of type 'System.NullReferenceException' occurred in ExerciseTracker.exe

Additional information: Object reference not set to an instance of an object.

I have a class with myString variable then I have set function where I say

myString = gcnew String("Hi there");

Then I get the error I put above.





Re: Visual C++ Language How do I allocate memory for a String^?

Shakje

Is it on that line that it breaks

Post the code that declares the string in the class (not the whole class), and the function that sets it.






Re: Visual C++ Language How do I allocate memory for a String^?

Nishant Sivakumar

It could be that that line of code is in a method of an object that has not been instantiated yet (so 'this' is null). Check if that's the case.





Re: Visual C++ Language How do I allocate memory for a String^?

Corey Was Here

Heres just a quick example I made. It makes it to the MessageBox then I get the error when it reaches my String .

settest.h

#pragma once

using namespace System;

ref class settest

{

public:

settest(void);

void setString();

public:

virtual ~settest(void);

protected:

String^ Corey;

};

settest.cpp

#include "StdAfx.h"

#include "settest.h"

settest:Tongue Tiedettest(void)

{

}

settest::~settest(void)

{

}

void settest:Tongue TiedetString(){

System::Windows::Forms::MessageBox:Tongue Tiedhow("Here");

Corey = gcnew String("Corey");

}





Re: Visual C++ Language How do I allocate memory for a String^?

Nishant Sivakumar

Can you show how you invoke that class




Re: Visual C++ Language How do I allocate memory for a String^?

n0n4m3

Hi,
it's probably what Nishant Sivakumar pointed, you have somewhere:

settest^ test;
test->SetString();

And this will crash because test is not instantiated yet. Try:

settest^ test = gcnew settest();
test->SetString();