Advertisement

array pointer confusion!

Started by August 25, 2000 06:31 AM
3 comments, last by stevenmarky 24 years, 4 months ago
I''m reprogramming a Snake game I made a while ago. In my old version the Snakes were functions, but since I''ve learned a lot and now have the Snake as a class. I keep the Snakes X and Y positions in an array[100] in the Snake class. I need to retrieve this information from the class, because I need individual instances of the class to interact. And I can''t return an array from a function(!) so I have realised I will have to use references or pointers, which I am unfamiliar with. How do I do this? Which do I use, references or pointers? I know it a fairly easy question. Can you give me a code example? DX++ The DirectX Programming Site
actually you can return a pointer to an array from a function i think...
eg

char *something()
{ char buffer[20];
sprintf(buffer,"something");
return buffer;
}

but if you need to retrieve that information then why not just have a function that will return it then?

or you could have it return a datatype containing the information..


you were a little vague in your explanation u know

Advertisement
quote: actually you can return a pointer to an array from a function i think...
eg

char *something()
{ char buffer[20];
sprintf(buffer,"something");
return buffer;
}


You shouldn''t return a pointer to a local variable, because the local variable is destroyed when the function returns.

-Jussi
ok. I''ll make it more clear.

I have a class that contains a private array.
I want to access this array from outside the class methods(functions).

How do I do it?



DX++ The DirectX Programming Site
You should write a "get"-function:
    class Snake{int m_X_positions[100];public:int *get_X_array();};int *Snake::get_X_array(){return m_X_positions;}//Now, to access the data somewhere, you write for exampleint *red_snake_Xpos;//declare a pointerred_snake_Xpos = red_snake.get_X_array();//retrieve arrayred_snake_Xpos[30] = 3;//write to the array.    

Now, that''s for a one-dimensional array. If you have a two-dimensional (int i[10][20]), it''s a little different, but not much.

My first game was also snake!
//Ksero

This topic is closed to new replies.

Advertisement