Using pointers?

Hello. I'm trying to get into pointers.
Let's say this was real program.
1
2
3
4
5
6
7
8
//...
else if (mood == "drunk")
	{
		const double tip = bill*0.15;
		const double n = find_first_digit(tip);
		cout << setprecision(5)<< pow(tip, n) << endl;
	}
//... 

Wouldn't be nice if tip and n were pointers which I could delete? If so, how do I do it?
I dont see why it would be nice to have them be pointers. But either way, since you mentioned you wanted to delete them, I assume you want to allocate memory. Here -

1
2
3
4
5
6
7
double* tip = new double;
	tip = bill*0.15;
	double* n = new double;
	n = find_first_digit(tip);

	delete tip;
	delete n;


http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
TarikNeaj,
Well, isn't that the main purpose of the pointers (to create and delete something during the program)?
Not necessarily. Pointers are also used with arrays. You cant pass an array to a function without a pointer.

Lots of threads to read.

http://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself

http://stackoverflow.com/questions/162941/why-use-pointers

Edit: Thought [] and * was the same when passing an array to a function, my bad.
Last edited on
Well, isn't that the main purpose of the pointers (to create and delete something during the program)?

the main purpose of a pointer is to point to a section a memory for a certain amount of time.


You cant pass an array to a function without a pointer.

yes you can. this is perfectly valid c++:
1
2
3
4
5
6
7
8
void foo(int arr[]) {
    std::cout << arr;
}

int main(int argc, char *argv[]) {
    int arr[] = {1, 2, 3, 4, 5};
    foo(arr);
}
TarikNeaj,
I will read this stuff. So, in the code you wrote I could treat n and tip like ordinary variables?
Yes.
Topic archived. No new replies allowed.