Off Topic > Off Topic

Programming Megathread

Pages: << < (230/241) > >>

Gytyyhgfffff:

i'm not well versed on pointers or have much experience with anything outside of scripting languages for that matter so could someone explain why use pointers in the first place
like why do book *x = y when you can just do book x = y

Pecon:

Usually it's to save memory. If you pass a normal variable into a function and it returns a changed value that you just want to update your variable with, you end up copying your data into three different memory addresses, because each new instance of a variable is basically a copy. If instead you used a pointer, you declare your value once and then pass the pointer into the function where the function is then able to access and manipulatethat value directly rather than needing to hand around a bunch of copies of it.

On mobile, sorry if my explanation is kinda roundabout.

Ipquarx:

Well it has a lot of uses. First off, it's faster and more efficient because you don't have to constantly copy and allocate more memory to keep all the data in, which is especially useful when you have pieces of data that are gigantic and take up multiple megabytes of memory.

Second, it allows you to have a function that edits variables in the caller. Let's say you had one function like this (This is just generic pseudocode that uses C-style pointer syntax):

function initializeNumbers()
{
    Number *a, *b;
    *a = 5;
    *b = 8;
}

Then how would you go about adding these numbers together and put the result in A?
Well, you could do this (Using the * operator to de-reference):

*a = *a + *b;

But if instead of adding you're doing some much more complex operation, you might want to break it up into different functions. So instead, you could do this:
function add(Number* a, Number* b)
{
    *a = *a + *b;
}

function initializeNumbers()
{
    Number *a, *b;
    *a = 5;
    *b = 8;

    add(a, b);
    printLine(a, b);
}

to print out 13 and 8.

Third, it lets you represent the absence of data. If you have a non-pointer object, it could consist entirely of zeros, but those zeros do not indicate an absence of data, the data IS zeros.
If you want to represent an absence of data, you just have to set the pointer to null.

SUSHI:

You can also get pointers to functions which is extremely useful for making generic data structures and algorithms.

void func1( void )
{
    printf( "func1 called" );    
}

void func2( void )
{
    printf( "func2 called" );
}

void call( void(*func)( void ) )
{
    func();
}

void main( void )
{
    call( &func1 );
    call( &func2 );
}

Meldaril:


--- Quote from: SUSHI on April 19, 2017, 05:01:48 PM ---
--- End quote ---

I once used two function pointers to get the size of a function. Very dangerous but possible on certain systems and compiler outputs. I think MSbuild pads around procedures/functions to mitigate againt ROP attacks.

Pages: << < (230/241) > >>

Go to full version