whats the big deal about pointers in C? i mean why would i need to access variable's address anyway? give me some example user, why should i use pointers at all?
Pointers
Other urls found in this thread:
en.wikipedia.org
benchmarksgame.alioth.debian.org
twitter.com
If you don't get the point of pointers, you don't need them. It's that simple.
You'll understand them, once you have to solve a problem that requires manual memory management.
They're good for manual memory management. If you have an array with 10,000 entries that's accessed during lots of function calls it's inconvenient to pass all those 10,000 values to the function and then get a modified array as a return value, because you'd be copying all those 10,000 values all the time even if you change only one of them at a time. So instead of doing that you tell the function where to find the array of 10,000 values, by passing the function a pointer, and then it can access and modify it in place.
Many other, higher level languages (say, Python) let you do this without giving you the memory addresses, but they do that by abstracting the pointer away and freeing the memory automatically when it's no longer used. C is meant to be fairly close to the hardware and simple to implement, so that kind of abstraction doesn't fit the language.
Sticky
A pointer is just a memory location. It's the lowest level of control you have over the computer. If you don't find yourself needing pointers, that's only because the language you use has abstracted them out for your convenience. But those abstractions both limit your control, and slow things down. This is why C is so much faster than other languages.
...
when you want to carry a specific instance of a variable out of scope without copying.
here's an exemple:
imagine making an RTS. You have two character. You have to select one of them in order to use it. You have to make a pointer that point to the structure character. Lets declare it this way: Character *player. Now that you have that variable you just have to do: player = &character; From there you can use the the player as if it was the character. You could always change character by making the pointer point to another character.
here's another exemple:
let's say you make a list of element with an array and no pointer. You want to delet one element. You erase it and change everyone place by one. This cost O(n). Really bad. If you made a pointer instead you would just take the pointer that point from x to y and change it to x to z. Thus skipping y. You couold also delet y while you're at it. This cost O(1), which is the best thing you could have.
but that's wrong
Try to get through a full week in your Intro to C class before asking something like this.
...
Say you have a 1MB data structure that needs to be processed by multiple functions. If you didn't have pointers you would need to make a new copy of that structure in each function and then copy the updated version of that structure back to the calling functions.
With pointers you just pass the location of the structure in memory as an arguement, and the functions all access the same location.
A more generalised idea of pointers is to allow access to variables from outside the scope they're declared in. Ie if I have a function FN1 with variables A, B, and C, and I call a function FN2 and pass it the address of A, I can modify A in FN1 from FN2. This idea expands out to dynamically allocated objects which don't have a scope and so have to be accessed via pointers.
Every other language that implements references is just hiding away pointers.
well done op
How else are you going to pass data structures to a function? The only other way is to pass a copy of the variable, and that won't be efficient at all when you're talking about large arrays or structs. Also when you pass a copy, the function that's being called can't modify the variable in-place. So you either end up using lots of global variables, or you're stuck with functions that don't do much.
And so, even many functions in the standard C library make use of pointers.
And yet the CIA niggers OS slows you down, with all that virtual memory and context switching crap.
N O T E C H A L L O W E D
Allowed, in the sticky. There is already a C thread also.
Pass strings as function arguments, my weaboo friend.
It can't be done without fucking pointers.
Go back to reading your K&R. You ARE using a book like K&R and don't just google/wikipedia some half-baked pseudo knowledge together, right?
Pointers don't have anything to do with C. CS classes are just extremely dumbed down so C is the only language with pointers that kids learn.
Underrated post. This is also pretty much how C++ vectors are used as well.
void foo(vector& dat) { // do stuff in-place to sequential float data}int main() {vector muh_dat(10'000);iota(begin(muh_dat), end(muh_dat));foo(muh_dat);}
C++ performs much more rigorous compile-time type checking however.
If pointers are so great then why does everyone recommend to never use them?
CHECKMATE
I have never been recommended this, only that you should be careful.
This is horseshit.
Even in Java this isn't true, arrays are references to the memory and not the memory itself.
Because in C, function parameters are passed by value, not by reference. Not using pointers can cause lots of unnecessary memory usage.
There are multiple reasons:
Function parameters are passed by value in C (except for arrays), so if you want to change the value of a parameter you have to pass a pointer to it and then change the object that is being pointed at:
// wrong because you are only getting a copy of xvoid mutate_to_three(int x) { x = 3;}x = 5;mutate_to_three(x);printf("%d", x); // prints 5// correctvoid mutate_to_three(int *x) { *x = 3; // value sitting at address 'x' is 3}x = 5;mutate_to_three(x);printf("%d", x); // prints 3
Note that in the correct version the variable x is of type int, but the argument x is of type pointer to int.
If you have a huge structure copying it would be a waste of memory. By passing a pointer to it instead you tell the code "this is where the object is, look it up there".
This is particularly useful when you want to build lists or trees or other structures that aren't some "block"-like piece of data:
// A binary tree nodestruct node { struct node *left_child, struct node *right_child,}
The nodes don't have to be adjacent in memory.
Continuing the above, if you want to mutate your tree you need to change what the nodes are pointing at. Here we will swap the left child of two nodes:
void swap_left_child(struct node *n1, struct node *n2) { struct node *temp = n1->left_child; n1->left_child = n2->left_child; n2->left_child = temp;}
Note that we also passed the two nodes as pointers because we wanted to mutate existing nodes instead of creating new ones.
You cannot return more than one value. If you wanted to build up some structure and return an error code you would have to pick to return only one and write the other into memory directly:
int build_node(struct node *n) { n = some_other_function(); return n ? 1 : 0;}struct node *n = NULL;int success = build_node(&n);if (!success) { goto fail;}
Some people do it the other way around where they return the node and instead pass the error object by reference. It doesn't really matter.
Arrays and pointers are not the same thing in C, but if you pass an array as an argument you always get a pointer to the first element instead of a copy of the array:
void change_third_element(int a[]) { sizeof a; // e.g. 4 or whatever the size of a pointer is a[2] = 7;}int a [100];sizeof a; // 100a[2]; // some garbage valuechange_third_element(a);a[2]; // 7, a has been mutated
There might be more uses, but those are the ones off the top of my head. Other languages will "automatically" decide when to pass parameters by value and when by reference, but C doesn't hide things from you.
Beware of thinking every language is like C.
Pointers, as in raw pointers, are only good for manual memory management. If you don't care about data alignment to take full advantage of cache hits and misses, any language with references (read: any language without raw pointers) will do.
If you don't know why would you ever want to use a reference, though, you better start re-reading your books, though.
What the hell am I seeing here?
Another reason I forgot about
Your process has two regions of memory at its disposal: stack and heap. The stack memory will be released automatically when a function returns, so if you want an object to persist you will have to manually manage its memory and you access its memory location through a pointer:
struct node *n = malloc(sizeof(struct node));build_node(n);// when you are done with itfree(n);n = NULL;
Even if the function you allocated the node in returns the node will remain in memory. Of course you have to clean up the memory eventually when you no longer need the node anymore, otherwise you get a memory leak. You do not free memory on the stack, that part is automatic.
Other languages use the heap as well for certain objects (usually instances of classes) automatically and they clean up the heap memory automatically using a Garbage Collector or Reference Counting, but those things come at a runtime cost.
That's the
part.
Perl arrays are indicated by @ prefix in the variable name.
A backslash in front of variable gives you a reference to it.
The underscore array @_ is how a function accesses its arguments.
scalar(@_) is the length of that array.
When you pass the array itself, 10000 elements are copied into @_, but only the reference itself is copied when you pass by reference.
Oh, thanks for the comprehensible explanation. I was mostly following the program correctly until I found the scalar thing and completely lost myself.
However, does Perl abstract these things, or does it work exactly as intended? As in, does passing by value actually copy the whole array, or does it just make it appear to the programmer it has been copied? Also, how do you work with references?
Yeah, passing by value really does copy the array. I don't know why it's like this. Maybe because C arrays are static, and Perl ones aren't (you can grow or shrink them, and so on at your leisure).
References containt the memory address of the variable that's pointed to. If you print out a reference, it shows two things: the type of variable it's pointing to, and its address.
Since references are all scalar variables, and scalars are indicated with a $ prefix, you dereference them by prefixing the whole thing with the type of variable it's pointing to. For example:
$name = "Richard";$name_ref = \$name;print "RMS's first name is $$name_ref\n";@hobbit = ("Bilbo", "Frodo", "Sam");$hobbit_ref = \@hobbit;print "Gandalf met with: @$hobbit_ref\n";
I modified the earlier program to show the memory addresses. $_[0] is the first element of array @_ (that's how you access array elements, since they're individual scalar values).
It's clear that referencing the @_ in by_val() points to a different memory location than the @series array in main(), whereas the single reference passed to by_ref() points to the same exact location.
Nice taste friendo
THAT'S THE POINT
High-level language that use automatic pass-by-reference do so exactly to avoid using pass-by-value when it's inefficient to move big values around. It's no different in C, except that the programmer has to do it manually (unless you use malloc() and memcpy() with all array types to enforce pass-by-value everywhere)
Because you can fit sixteen to a cache line and the CPU doesn't have dedicated silicon to speed up your borrow checker or JSON.parse calls, you twat.
If you're storing 100 gold bars in a mailbox and someone buys it from you and wants their gold, it's easier to give them the key and mailbox # than to move all of it into their mailbox.
thats fuckin good explanation user
learn assembly newfag
we recommend that YOU don't use them.
...
what did he mean by this
...
Use Rust, retard.
most retarded post i've seen all day, congratulations
I know what pointers are for but I don't get why there are multiple pointers like int***. Can someone provide example?
They're pointers to pointers. You can use them for multi-dimensional arrays. For example:int **x = malloc(2 * sizeof(int *));x[0] = malloc(2 * sizeof(int));x[1] = malloc(2 * sizeof(int));x[0][0] = 1;x[0][1] = 5;x[1][0] = 8;x[1][1] = -43;
Who is that megane goddess?
artist is "rizky (strated)"
also goes by "riki-to"
I dont' think it's from a show or anything
Can also be for when memory is allocated inside of a function but the address is used outside of it with the return value of the function being an error code.
int fn(int **p) { *p = malloc(some_input_fn() * sizeof(int)); if (*p) return 0; else return 1;}int *x = NULL;int ec = fn(&p);
...
A multidimentional array is an array of arrays, that's just an array of pointers, it's completely retarded to make it like so, you have an indirection and multiple allocations scattered all over your heap.
It's only useful for things like argv where each array has a different variable size and you need them to be independent from each other.
If you need, for example an array of 5 rows, each with 4 elements, you can make it like so:
int (*x)[4] = malloc(4 * 5 * sizeof(int));x[0][0] = 1;x[0][1] = 5;x[1][0] = 8;x[1][1] = -43;
Note that it is only necessary to specify the amount of elements per row in the type declaration, that way the variable will point to elements of type int[4], which is what you need. The parenthesis differentiates this from "Array of 4 pointers to int".
Rust is useless for low level, you'd be better off with Perl, that's how ridiculously bad Rust is
That's a pretty extreme claim. Would you happen to have arguments?
It's slow as fuck and harder to learn/use than Perl.
Seems pretty fast to me.
benchmarksgame.alioth.debian.org
Being harder to learn than Perl is completely fine. Perl is supposed to be easy for doing quick and dirty things in, Rust is supposed to be very safe even when doing low-level things.
I bought bjorn strostroups's c++ book when I was younger and got to the end of chapter 1 and gave up.
I read it's not for absolute beginners though (assuming you were then). I've just started "Beginning C++ through Game Programming" by Michael Dawson (pirated), has anyone else used it before?
dumb animeposter
use ada you inane idiot.
30 years of development, dev tools / libraries / language well supported, stable. it's the standard (even mandated by contract in some cases) for absolutely-cannot-fail-or-people-die code.
A lot of people I know use them for weird data structures like balanced binary trees with split/merge functionality.
IOW yeah, they are usually unnecessary.
...
To be basic, they make it easier to have a function take a variable and actually be able to directly change it, instead of overwriting it or using the function return.
I have to leave this place for a while, there are too many faggots like you either baiting or making shit threads like this, for fucks sake.
Post PDF pl0x
Check me palindrome get
man just google it
So you're the humongous faggot who revived this enormously shit thread that we all thought to be thankfully dead.
GAS YOURSELF
I MEAN IT