why do ppl use pointers> can they just acces cant other then directly?
Printable View
why do ppl use pointers> can they just acces cant other then directly?
what...........hmmm........English please...!!??
I think the most common use is to make a function affect more than one variable.
Say you want to change the X and Y position of something on the screen. Your function could return one value to be assigned to either X or Y, but not both. You can pass-in as many pointers as you wish. So your function could directly change both X and Y.
what the hell is going on, i replied to the same thread as this!!!! http://cboard.cprogramming.com/showt...hreadid=33324, the id's have change! what the hell is going on?
Ummm... Also, when you pass a variable to a function, you're NOT passing the variable. You are passing the VALUE of the variable. In fact this is called "passing by value". Often the variable name is even different inside the function. (This can be confusing for beginners.)
fine everyone, just ignore me! deltabird - did i not reply to your thread, and you said thankyou! I need some evidence....
illustration...
Code:#include <iostream>
using namespace std;
void swap_incorrect(int var1, int var2)
{
int temp;
temp = var1;
var1 = var2;
var2 = temp;
}
void swap_correct(int *var1, int *var2)
{
int temp;
temp = *var1;
*var1 = *var2;
*var2 = temp;
}
int main()
{
int var1 = 5;
int var2 = 10;
cout << "default : " << var1 << ' ' << var2;
swap_incorrect(var1, var2);
cout << "\nswap incorrectly: " << var1 << ' ' << var2;
swap_correct(&var1, &var2);
cout << "\nswap correctly: " << var1 << ' ' << var2;
cout << endl << endl;
return 0;
}
I saw a similar question, and your answer. That thread is gone now (deleted I presume). oh well..Quote:
Originally posted by subdene
fine everyone, just ignore me! deltabird - did i not reply to your thread, and you said thankyou! I need some evidence....
ahh, thank you! thought i wasn't going mad. wonder why they deleted it? anyways..........
Along with the reasons given above, pointers are necessary for runtime polymorphism, i.e. a combo with virtual functions.
Also necessary for arrays as they technically cannot be passed to a function as a whole, only the address is passed. Thats much more efficient. And using pointer arithmetic to access array elements is executed faster than indexing an array. [I dont know the details about that fact, but it just is]
Almost forgot. Strings - pointers are a must for working with strings. Frankly, I dont know how Java-ers manage. :)