![]() |
|
[C++] Pointers - Printable Version +- LCKB (https://lckb.dev/forum) +-- Forum: ** OLD LCKB DATABASE ** (https://lckb.dev/forum/forumdisplay.php?fid=109) +--- Forum: Programmers Gateway (https://lckb.dev/forum/forumdisplay.php?fid=196) +---- Forum: Coders Talk (https://lckb.dev/forum/forumdisplay.php?fid=192) +---- Thread: [C++] Pointers (/showthread.php?tid=666) |
- Wizatek - 02-12-2012 Hi, Im still a little vague in when to use pointers. I have a c# background and those kind of things all get managed by the framework. I know how a pointer works, and what it is. But i dont understand exactly yet when its best to use a pointer and when its best to just use a value type ? I have been reading about it, but it didnt made me any smarter - someone - 02-12-2012 Pointers usually is used for dynamic allocation of data, passing argument s of a function by references. For example in C# all classes are declared as Pointers(In C# ref is the alternative of pointer, or the unsafe). You want to allocate a number of instances; An wrong example: int size= 10; int b ; a good example would be: int size = 10; int *b = new int[size]; Passing Generic parameters to a function to return multiple types of data. void switch(int *a, int *b){ int tmp; tmp = *a; *a =*b; *b = tmp; } Another example is pointers of functions: Usually used to get the function address from a dll loaded with Load library, or get a function address of a current function, or create an array of functions: void (*Menus[])(PLAYER *player) = { SaveMenu, LoadMenu, OptionsMenu }; Creating Design Patterns(example singlethon). template class singleton{ private: static T* instance; public: static T* GetInstance(){ if( instance ==NULL){ instance = new T(); } return instance; } }; Simple try to use Pointers when you have low resources and dont want to waste them, create allocating and dealocating bytes in memory(Memory management). Since a pointer is only a label(attaches only to the address in memory). Here is a code that will crash a computer(DOS OPERATING SYSTEM) using pointers: /* --crashdos.c-- */ void main(){ unsigned char *ptr; int i; ptr = (unsigned char *)0x0; for(i=0;i<1024;i++) { ptr[i]=0x0; } return; } - Wizatek - 02-12-2012 ok i think i get it a bit better now. Specially the return multiple types of data is nice, i came to a few situations already where i wanted to return multiple different types of data, and i just ended up returning a array of objects ![]() I also realise that with all the pointers and references used it takes much more work remembering what is used where while coding. But maybe (i hope) it gets easier over time - Jackster - 02-12-2012 That is how I feel after reading that. Sorry could not help it. |