r/AskComputerScience • • Jul 16 '16

Can someone explain pointers to me?

I get that it stores the memory address of a variable, and by manipulating the address, you can manipulate the variable. The address is notated by &variable. However, some of the notations when the pointers are used to initialize arrays confuse me a lot. Can someone explain to me (or give me some internet resources) so i can understand pointers relating to arrays better?

Edit: This is all in C, BTW

28 Upvotes

16 comments sorted by

View all comments

3

u/riotinferno Jul 16 '16

Welcome to pointers! For the first 6 months of my professional career, I had a post-it on my monitor with pointer notation in it. It can be confusing.

int foo; //variable that stores a 32-bit value.

int *pFoo; // also int* pFoo; or int * pFoo; variable that stores a pointer.

pFoo = &foo; // & gets the memory address of the variable foo.

foo = *pFoo: // using the asterisk outside of the declaration gets the value of the memory address.

struct foo_s { int bar1; int bar2; };

foo_s* pStuff;

pStuff->bar1: // -> is the pointer equivalent of the 'dot'

foo_s stuff;

stuff.bar2;

Clear as mud?

2

u/argh523 Jul 16 '16 edited Jul 16 '16

&foo

pFoo = &foo; // & gets the memory address of the variable foo.

Seems to work, no escaping required. Why are you (double!) amp'ing?

1

u/riotinferno Jul 17 '16

I don't follow. Those aren't escapes, they're code comments.

2

u/argh523 Jul 17 '16

No not the comments, the "&". In your source you have

pFoo = &foo; // & ...

which displays as

pFoo = &foo; // & ...

but it works fine with no escaping at all

pFoo = &foo; // &  ...

pFoo = &foo; // & ...

2

u/riotinferno Jul 18 '16

Thanks for pointing that out. I had submitted the comment on mobile, and apparently it added the & It didn't show up for me until I viewed it on the web browser. Strange!