What exactly is the purpose of the (asterisk) in pointers?

前端 未结 4 1194
有刺的猬
有刺的猬 2020-12-09 14:00

I\'m new to programming and I\'m trying to wrap my head around the idea of \'pointers\'.


int main()
{
    int x = 5;
    int *pointerToInteger = &         


        
4条回答
  •  情歌与酒
    2020-12-09 14:29

    One way to look at it, is that the variable in your source/code, say

    int a=0;
    

    Makes the 'int a' refer to a value in memory, 0. If we make a new variable, this time a (potentially smaller) "int pointer", int *, and have it point to the &a (address of a)

    int*p_a=&a; //(`p_a` meaning pointer to `a` see Hungarian notation)
    

    Hungarian notation wiki

    we get p_a that points to what the value &a is. Your talking about what is at the address of a now tho, and the *p_a is a pointer to whatever is at the &a (address of a).

    This has uses when you want to modify a value in memory, without creating a duplicate container.

    p_a itself has a footprint in memory however (potentially smaller than a itself) and when you cout< you will write whatever the pointer address is, not whats there. *p_a however will be &a.

    p_a is normally smaller than a itself, since its just a pointer to memory and not the value itself. Does that make sense? A vector of pointers will be easier to manage than a vector of values, but they will do the same thing in many regards.

提交回复
热议问题