Advertisement

add variables to the variablename

Started by January 28, 2003 01:31 PM
5 comments, last by Metalchild 21 years, 9 months ago
hi, is there a possibility to make this possible? what i mean: for example i got a loop: for(int i=0;i<50;i++) { int abc; } so, and i want that the name of the variable isn''t abc, it shall be abc1,abc2 etc. is this possible and when yes how?
I would suggest using an array instead. Then it would be abc[1], abc[2], abc[3] etc.
Advertisement
ok, you're right.

and i gotta say something (i forgot)...

i need the numbers for a struct with an array:

for(int x=0; x < Fieldsize; x++)
{
for(int y=0; y < Fieldsize; y++)
{
Field NewField[x][y];
}
}

doesn't work, cause i gotta use constant values

[edited by - Metalchild on January 28, 2003 2:40:27 PM]

[edited by - Metalchild on January 28, 2003 2:41:51 PM]
Get memory from the heap.

Look up the "new" and "delete" operators for variable size arrays.
quote: Original post by Metalchild
for(int x=0; x < Fieldsize; x++){   for(int y=0; y < Fieldsize; y++)   {      Field NewField[x][y];   } } 



Remember that if you''re declaring a variable inside a loop you''ll not
have access to that data when you get out of that loop or your data may be
corrupted.

have a look at this:
int ArraySize = 10;int *Array = new int[ArraySize];if( !Array )   ... // Out of memoryelse{   ... // Do whatever you want to do with the array   delete[] Array;   Array = NULL; // This is optional, but you should set it to null so later you can check if the array is created to avoid memory leaks.} 


Hope that helps

KaMiKaZe
Kamikaze15, the standard default failure routine for the new operator is not to return NULL (0, whatever you want to call it ), it is to throw a std::bad_alloc exception.

This behaviour can be changed like this:
#include <new>// ...// Return NULL (0) on failurenew(std::nothrow) type [count];


Advertisement
Yes, you should be using arrays and dynamic memory. But as an FYI (in msvc land) you can use the __COUNTER__ macro to accomplish tacking numbers onto the end of a variable name (along with the ## operator).

This topic is closed to new replies.

Advertisement