melw82

Hi,

I am fairly new to C++ and I have a problem with declaration of variables.

I have an integer variable to a function which represents different datatypes, e.g. 1 for int, 2 for char, 3 for float, etc. Depending on its value, I need to create an array of this datatype. I tried using switch and if statements but I cannot do so because the local scope forbids me from using it later on. How should I go about doing the declaration

Thanks in advance.

Regards

Melvin



Re: Visual C++ Language Declaration problem

Jonathan Caves - MSFT

It is not clear exactly what you are trying to do: please show us some (not a lot!) of code so we can get a better idea.






Re: Visual C++ Language Declaration problem

melw82

Oh.. ok... this is an illustration of my case.

main(void)

{

int mytype;

cout<<"What array do you want to create ";

//Just assume user will enter 1 valid integer value

cin>>mytype;

myfunc(mytype);

}

void myfunc(int thistype)

{

//int

if(thistype==1)

{

int* myarray = new int[10];

}

else if(thistype==2)

{

char* myarray = new char[10];

}

else // float

{

float* myarray = new float[10];

}

// I want to do some manipulation with the elements in the array here

// but I can't because the array is destroyed in the respective blocks above

}





Re: Visual C++ Language Declaration problem

Ramkrishna Pawar

Define myarray as a structure type, like this,

Code Snippet

struct ExArray{

void* myarray;

DWORD dwType; // to identify if it was int*, char* or whatever, you will need to define few macros for this.

};

void myfunc(int thistype)

{

ExArray eArray ;

eArray.dwType =thistype;

if(thistype==1)

{

eArray.myarray = new int[10];

}

else if(thistype==2)

{

eArray.myarray = new char[10];

}

else // float

{

eArray.myarray = new float[10];

}

// Do whatever ...

}






Re: Visual C++ Language Declaration problem

melw82

Thanks a lot.. but I have another situation now.

What if I need a pointer to a pointer to an array I tried the following and I was prompted with an error because I was trying to change the type(in this case int** to void**), can I simply use casting I am not very sure how to do it.

struct ExArray{

void** myarray; //Changed to double pointer here!!

DWORD dwType;

};

void myfunc(int thistype)

{

ExArray eArray ;

eArray.dwType =thistype;

if(thistype==1)

{

eArray.myarray = new int*[10]; //Error here

for(int i=0;i<10;i++)
{
eArray.myarrayIdea = new int[10];
}

}

else if(thistype==2)

{

....

}

else // float

{

....

}

// Do whatever ...

}





Re: Visual C++ Language Declaration problem

einaros

Sure, you can cast it such as

eArray.myarray = reinterpret_cast<void**>(new int*[10]);