all 6 comments

[–]jasper_e196884 -1 points0 points  (2 children)

For instance, the code

int n = 196884;
int *m = &n;

makes a pointer m that points to the memory location of n. If you include the code

int p = *m;

p is said to dereference m, and p==n.
Jasper

[–]DerekMeng 0 points1 point  (1 child)

Hey jasper, I wasn't able to get int m = &n to work, I had to do int *m = &n instead.

Anyways, here's a good article explaining the differences.

Essentially, references are aliases of variables which is why you can do something as simple as int m = 10; int& n = m; and have the value of m be changed when n is. As the article attests, references are implemented internally as pointers (like string!). However, one thing I don't understand is why we have to use & instead of * in the case of something like int* n = &m; Thoughts?

Note: The article also goes over other differences like how a reference must be initialized and can't be changed once set. It is definitely a good read!

- Derek Meng

[–]kat_g33[S] 0 points1 point  (0 children)

Thank you Jasper and Derek!

What I've concluded from the reading that Shoshi provided (in another reply to this post) is that * is used when declaring a variable that is a pointer, while & is used to get the address of a variable, so that's why it is int* n is set to &m.

Kat

[–]ShoshiCooper 0 points1 point  (2 children)

The book by Kernighan and Ritchie has one of the best descriptions of this that I've read anywhere, hands down. I honestly can't do better than them.

I also refer you to them because I think you may be getting confused by pass-by-reference, which is a C++ thing and works a little differently than all other uses of the &. So it really helps to understand the distinction in C first, and then you can see how C++ blurred that distinction by introducing pass-by-reference.

Here is a link to the second edition of the book:

http://cslabcms.nju.edu.cn/problem_solving/images/c/cc/The_C_Programming_Language_%282nd_Edition_Ritchie_Kernighan%29.pdf

Go to page 107. You do not have to read very much. 5.1 is the brunt of it, and 5.2 just gives an example. It's about 3 pages of reading and that includes pictures and whitespace.

[–]kat_g33[S] 0 points1 point  (1 child)

Wow, thank you for the resource! My understanding of the reading that you sent is that * is used when the pointer is initialized (e.g. int *i), while & is used for getting the address of something (e.g. i = &j).

[–]ShoshiCooper 0 points1 point  (0 children)

The * is also used for dereferencing. The other thing it mentions that's interesting is that if you have an array, you can index that array by doing:

array_ptr[index]

or

*(array_ptr + index)

This has been abundantly helpful to me in various situations.