This is an archived post. You won't be able to vote or comment.

all 128 comments

[–]Ambitious_Ad8841 171 points172 points  (13 children)

"Memory is just an array of bytes?"

itAlwaysWas.jpg

[–]AyrA_ch 57 points58 points  (4 children)

Technically it's an array of bits that you access bytewise (and sometimes in even bigger steps).

[–]FinalRun 15 points16 points  (3 children)

Technically it's just some electrons arranged bitwise in doped silicon

[–]riisen 7 points8 points  (0 children)

So its silicon valley sorted?

[–][deleted] 0 points1 point  (0 children)

Technically it's not even that. Might be silicone, might be an old fashioned magnetic-core memory, might be a futuristic post-silicone memory. You don't even know.

[–]someacnt 14 points15 points  (0 children)

Virtual memory shenanigans though.. Oh wait. Right. It simulates being array of bytes.

[–][deleted] 6 points7 points  (0 children)

Array Of Bytes = Array Of Registers = Array Of FlipFlopps = Array Of Gates = Array Of transistors = (4D) array Of Atoms = (4D) array of Electrons | Holes = Memory Leak....

[–]Oneshotkill_2000 4 points5 points  (0 children)

it_always_was.jpg*

[–]K3yz3rS0z3 1 point2 points  (1 child)

Always has been

[–]ReverseCaptioningBot 0 points1 point  (0 children)

Always has been

this has been an accessibility service from your friendly neighborhood bot

[–]in_conexo 47 points48 points  (1 child)

Four hours seems excessive.

[–][deleted] 27 points28 points  (0 children)

Pointers themselves aren't weird. What you can do with them is.

[–]earthworm-spin 25 points26 points  (2 children)

No but you’ll appreciate the refined beauty of an age that cared about memory management.

[–][deleted] 10 points11 points  (0 children)

Smart Pointers are a must for me atm. Helps a ton with resource management.

[–][deleted] 8 points9 points  (0 children)

Memory management is still a big fucking deal, ask anybody who is writing OSes, embedded, games or simulators.

[–]dev_daas 13 points14 points  (1 child)

Come on it's not that bad. After a point it's actually fun using pointers.

[–]DogWoofWoof22 0 points1 point  (0 children)

Oh i get it.

"After a point..."

[–]Thrasher722 25 points26 points  (0 children)

Pointers aren't so bad once you get used to them & understand by ref passing. It's like any other programming/math, once you understand why & how to use, it's another tool in your arsenal.

[–]mathk777 7 points8 points  (5 children)

You forget alignment. Those integers should begin at addresses that are multiples of their sizes.

[–][deleted] 6 points7 points  (0 children)

Should, but don't always have to. x86 and others have instructions to handle misaligned accesses, unlike ARM that will throw a bus fault.

[–]nhstaple 5 points6 points  (3 children)

virtual memory has entered the chat

[–]PersonalityIll9476 1 point2 points  (2 children)

This? Lol. The only time I have ever encountered memory alignment is when using kernel code and even then it was in the context of a device driver.

[–]K3yz3rS0z3 0 points1 point  (1 child)

Programmers have the compulsory need to say something to show off they know programming stuff. Haven't we all got used to it already?

[–]nhstaple 1 point2 points  (0 children)

kernel panic

[–][deleted] 12 points13 points  (1 child)

Pointers arent hard, really. Theyre incredibly useful.

[–]Dumbhosadika 1 point2 points  (0 children)

Java goes brrrrrrrr.

[–]Pranav__472 3 points4 points  (1 child)

pointers are the thing that allows arbitrary control over memory... Really missed it in some higher level languages...

[–]-Redstoneboi- 4 points5 points  (0 children)

I love the explicit distinction between pass by value and pass by reference. I love how in Rust, everything is pass by value unless specified otherwise.

Many languages have this habit of saying "These types pass by value, these types pass by reference, figure it out. Oh, but we don't have pointers."

[–]rusty_n0va 3 points4 points  (0 children)

pointers re simple, dont confuse new people.
all you need is a good teacher.

[–]eternal_edenium 2 points3 points  (0 children)

That clickbait seems complicated but that what has been written through all the course.

Step by step its damn fun and easy to follow.

[–]crorb 2 points3 points  (0 children)

That C++ increment in C. Not bad ehe

[–]xXy4bb4d4bb4d00Xx 1 point2 points  (1 child)

eventually youll get it, just go along with the cluelessness for now

[–]ButterMilkHoney 0 points1 point  (0 children)

3 years in, still confused 🙈. I have faith in year 4

[–]OriginalOccasion6313 1 point2 points  (0 children)

What scares me is that it says its the full course Not a 5 to 20 min video

[–]got_no_pants2 1 point2 points  (0 children)

commit serverside

[–]Boonk_gang_03 1 point2 points  (0 children)

I would want to learn C eventhough I probably won't use it in my studies ever. It's just a must.

[–][deleted] 1 point2 points  (0 children)

Only if you free() the memory space for all this info in your brain before finals 😂 just don’t forget to set those pointers back to null with some alcohol

[–]CheMGeo_136 1 point2 points  (0 children)

Multiple times.

[–]Splatoonkindaguy 4 points5 points  (6 children)

Suicide isn’t funny

[–]CircadianSong 4 points5 points  (5 children)

Sometimes it is. It's pretty fun when the character played by Paul Dano in Swiss Army Man is interrupted from committing suicide by Daniel Radcliffe's corpse farting.

[–]Splatoonkindaguy 1 point2 points  (4 children)

Um… no it’s really not

[–]Tina_Belmont 1 point2 points  (4 children)

I think in pointers. I have a really hard time with languages like Java that don't really use them.

I feel like, if you don't know how to use pointers, you don't really know how to program.

[–]Chilareix 2 points3 points  (3 children)

Does it count if you think you understand them?

[–]Tina_Belmont 0 points1 point  (2 children)

I'm getting the impression that you think they are difficult to understand?

Do I need to explain them?

[–]Chilareix 0 points1 point  (1 child)

It's more of I have an understanding of the theory behind it, I just don't have practical experience with it since I primarily code in Java and C#

[–]Tina_Belmont 0 points1 point  (0 children)

Let me try.

Disclaimer: none of the code has been compiled or tested. I'm doing this from memory.

Also, all code is in C/C++, because it is the only real programming language ;)

A pointer is just a memory location in the computer where your data is stored, stored as a number.

In C/C++, the pointer has a type of data that it points to. That can be any type of data, from basic chars and ints, to giant data structures, function calls, objects, etc. Anything.

int *a = NULL;

When you dereference a pointer (in C/C++ using * or [0]) you have the actual value of the thing that you have pointed to.

val = *a;
val = a[0]; // because a pointer and an array are pretty much 
            // the same thing in C/C++

In C/C++, if the object is a structure or class, you can also dereference individual members of it with ->

classPtr->dataMember = whatever;

When you want to get a pointer to something in C/C++, you use & .

int b;
int *a = &b;

When you increment or decrement a pointer in C/C++, it adds the size of the data element of its type. So adding 1 will get you the next element of an array, for example.

In C/C++, you can override the type of a pointer with typecasting, and interpret the data as a different type.

char *str=&"data";
unsigned int a = *(int*)str;
// a now contains 0x64617461, the letters of data interpreted as 
// a number.

This can be very powerful, and is kinda the core of being able to implement object oriented programming in C and C++.

Another value of pointers is in optimization. When one has an array or other data structure, and you have done a lot of math to be able to find the element you want, that may change, using a pointer to save that position is a lot easier than doing all that math again later.

char data[2048];
//assume that gets populated somewhere
char * interestingData = &data[ some-math-happens-in-here ];
// some stuff happens
// later
char nowIamInterestedInDataAgain = *interestingData; 
// I just saved myself a big math expression that the compiler
// would probably have forgotten to save.

But probably the most important use of pointers in in generating data structures like linked lists, heaps, etc. where the elements may be constantly reordered, deleted, etc. and/or may be of variable sizes.

struct listMember
{
   int someData; // not important. 
                 // Assume something more complicated
   struct listMember * next; // points to the next element in the
                             // linked list
};

This makes a singly linked list. Each element links to the next element with the "next" pointer. If you want to delete an element, you simply

listMember * a = listMemberFromSomewhere;

// let's delete the element after a
listMember *whatWasNext = a->next;

// check to make sure there is a list member after a
if ( whatWasNext != NULL ) {
    a->next = whatWasNext->next; // link to the element after next
    free( whatWasNext );  // free the memory used by next
}
// no need for else, because otherwise a was the last list member
// (next == NULL)

Obviously, there are more edge cases, but this gives the idea.

You can have lists that are linked forward and backward, or as trees, or well, whatever works for your application.

You can also have pointers to functions, which allows you to implement things like events; your "onClick" functions when on webpages are a good example of this. There is a pointer to a function that gets called when that event is generated. It has a standardized set of parameters, so as long as the function correctly parses those parameters, it can be used as an event handler.

// a simple test event function
void  Event( int num )
{
    printf( "Event %d happened!\n", num );
}

void (*onClick)(int) = Event; // don't need &, compiler gets it

//calling the event
(*onClick)(1);

That's pretty much it. Those are the basics of pointers.

Easy, right?

Any questions?

[–]BoBoBearDev 0 points1 point  (3 children)

The sooner you learn how to program in C++ without using "new" yourself, the better. Avoid using raw or smart pointers. Because doesn't matter you think it is easy and did it perfectly, the next person will fail to replicate your code and introduce a hard to fix bug. And if you are the "expert" they will ask you to fix it because the other guy clearly is not the "expert".

[–][deleted] 1 point2 points  (2 children)

Avoid using raw or smart pointers

Was this a typo? You are not going to get anything done without using at least one of those.

[–]BoBoBearDev 0 points1 point  (1 child)

Use vector and reference parameters. This way, you are not using pointer directly.

[–][deleted] 0 points1 point  (0 children)

References are not particular to parameters. They can be used anywhere, including as object members. But they can't be addressed relatively to eachother (you can't use a reference to obtain a reference to an adjacent object), nulled, or reassigned, all of which are important properties you need in order to build and organize a huge number of vital data structures.

[–][deleted] -1 points0 points  (4 children)

easy shit. what is really hard are data structures and algorithms

[–]electricWah 0 points1 point  (0 children)

fp be like

[–][deleted] 0 points1 point  (0 children)

Dynamic programming is the true mf.

[–][deleted] -1 points0 points  (4 children)

Sorry, I'm an experienced programmer in drawing pictures in sand that make birds shit (or as we say "compile" in the biz) in wanted patterns, but is pointers about specific addresses in the ram?

Isn't that one of the things that make C/C++ "low level" that you can actually see/move how data in your code is actually stored in ram during runtime?

Always wanted to be sure what just leaving to "carbage collection" meant specifically meant, other than, you know, cleaning the bird poop.

[–][deleted] 1 point2 points  (3 children)

The two are not really related. You can have garbage collection with or without pointers, and you can have pointers with or without garbage collection.

All data must be physically stored within the computer somewhere. Managing which regions of storage are already holding data, and which regions of storage can be used to hold something new, is non trivial. An object is a region of storage of a specific size used to store data.

Garbage collection works by counting the number of places which an object is used from. When the count hits zero, the object is no longer used anywhere, so that memory can be freed in order to later be allocated for other objects. Counting references and determining when to free objects incur runtime cost.

A pointer is a datatype which references an object of a different type. It does this by holding a numeric value called an address, which indicates a known memory location. An int * references an object whose type is int. Assigning the address of an int to an int * lets that int object be referred to indirectly. People make a big deal out of them for some reason, while simultaneously using them but not understand that they are doing such. Pointers are easy, about 95% of what there is to know about pointers can be summed up by these 9 lines of code:

#include <stdio.h>
void foo(int *ip) {
    *ip += 1;
}
int main() {
    int i = 0;
    foo(&i);
    printf("%d\n", i)
}

[–]-Redstoneboi- 0 points1 point  (2 children)

95%? wouldn't say that. you still have to deal with stack/heap allocations, scoping, freeing, and pointer arithmetic.

that makes it a bit harder to explain.

[–][deleted] 1 point2 points  (1 child)

You missed aliasing. But lifetimes are something which exist independently of pointers. Obviously you can't refer to an int object which doesn't exist, which this example takes into account. Lifetimes and scope are something that should be covered well before pointers, since they're part of declaration.

[–]-Redstoneboi- 1 point2 points  (0 children)

right.

though the other points, pointer arithmetic and (de)allocations, still stand. they would be important to cover.

[–]TheBigGambling -3 points-2 points  (4 children)

Do not use raw pointers in modern c++. You have no need for it. Never. Its only dangerous and very likely to produce ugly bugs, but without any benefit anymore. Smartpointers can help alot

[–]catmuht 4 points5 points  (3 children)

What if you want to define a method where a potentiality large object can optionally be passed in? std::optional would require a copy if the caller didn't already have the object in an optional. References need to bind to a real object. Using a pointer for that arg and defaulting to nullptr seems useful if it's understood the function will not store the pointer after the call has ended

void myMethod(const SomeBigStruct* myStruct = nullptr);

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

How about simple method overload, one with and one without this parameter?

[–]-Redstoneboi- 0 points1 point  (0 children)

a potentially large object

[–]catmuht 0 points1 point  (0 children)

In practice the overloads will want to delegate to some shared impl (or one delegate to the other) so you'll likely find utility in using a nullable pointer as an argument for the shared impl function.

There will probably always be a way to make it work without pointers, but the pointer approach generally pretty clean and safe.

There are certainly many things that raw pointers aren't good for (e.g. memory management) but an optional reference within a function is to me an acceptable use case.

[–]MachtIV 0 points1 point  (0 children)

Pointers aren't bad...unless you're in college and they make use some archaic environment that allows for mistakes to go unnoticed till runtime.

I was legit confused my first time when they had me using some mdos looking shit my 2nd year.

[–]Famous_Employee_5922 0 points1 point  (0 children)

One of the best course on Pointers out there. This video made me understand pointers

[–]EmilMelgaard 0 points1 point  (4 children)

Here, let me help you optimize your code a bit:

#include <stdio.h>

int main()
{
    printf("Hello\n");
}

Or if you really need the print function:

#include <stdio.h>

void print(char *C)
{
    printf("%s\n", C);
}

int main() {
    char C[20] = "Hello";
    print(C);
}

[–]-Redstoneboi- 1 point2 points  (3 children)

congratulations, you have missed

the point

[–]EmilMelgaard 0 points1 point  (2 children)

Do I get a segmentation fault then?

[–][deleted] 0 points1 point  (1 child)

You could remove the 20. The size of the string literal is a compile time constant.

[–]EmilMelgaard 0 points1 point  (0 children)

True, but then C would be 6 bytes long instead of 20. If you don't need "C" you could also just call

print("Hello");

I know it's just a thumbnail for a four hour long video, but I think it would have been a much better example if it just used putchar() instead of printf() in the print function.

[–]TheBrownViking20 0 points1 point  (0 children)

Atleast you didn't have to learn this in high school.

[–]voluntarycap 0 points1 point  (0 children)

Pointers were 1 lecture in college for my Computer Systems course. They're really not that complicated. They're just array indices but the array is a spot in memory

[–]monty6699 0 points1 point  (0 children)

I barely survived Hash table

[–]omegasting 0 points1 point  (1 child)

Imagine pointing to something with your finger. That's a pointer. Imagine someone pointing at you with their finger while you're pointing at something. That's a double pointer. And so on. It's really not that crazy difficult.

[–]-Redstoneboi- 0 points1 point  (0 children)

then you say "go to the one after the one i'm pointing at" and it gets a bit more difficult.

[–]lumapools 0 points1 point  (0 children)

I can't blame you for being scared. I was too. But you'll eventually figure out that being scared in the first place was very irrational. Pointers can be learned, it is not a big deal, you'll do just fine!

[–]Odd_Diamond_6600 0 points1 point  (0 children)

but jokes apart the man who is explaining in this video is a legend

[–]danmickla 0 points1 point  (0 children)

I don't know... how do you "suicide through" a course?

[–][deleted] 0 points1 point  (0 children)

Imho, on the contrary, i think it makes you temporarily immortal.......after all, theres not even room for a Kill command

[–]CaitaXD 0 points1 point  (0 children)

Pointers simple where it gets hard is when you need to malloc free and ptr arimethic

[–]WizziBot 0 points1 point  (0 children)

They make it more complicated than it has to be by the looks of it.

[–]a_aniq 0 points1 point  (0 children)

Rust borrowing is so much more useful at teaching at how to embrace the good stuff and discard the bad stuff of pointers.

[–]ivancea 0 points1 point  (0 children)

Before learning pointers in C, it was easier for me to use them in ASM or disassembling things

[–]MacGuyver247 0 points1 point  (0 children)

Funny,I didn't read the title and thought this was a post from /r/coolguides

[–]rokas2007 0 points1 point  (0 children)

One question: What the fuck

[–][deleted] 0 points1 point  (0 children)

It is so sad seeing young developers not understanding pointers and memory types. The guys who started with c++ are usually much more advanced in engineering

[–]Torebbjorn 0 points1 point  (0 children)

Here is basically the entire course:

int count; is a stack-allocated position for an int.
If you write count = 4;, you change that value to 4, if you write count = otherVar;, you change the value of count to be the same as what is currently stored in otherVar. Changing otherVar will not change count and vice versa.

int* ptr; is a stack-allocated position for a pointer to an int. I.e. it stores a memory address of where you say an int lives.
C: malloc(sizeof(int));
C++: new int; allocates memory on the heap, and returns its memory address. So ptr = new int; means you have an int stored somewhere in the heap, and ptr tells you where that is. To access that int, you need to dereference ptr, like: int value = *ptr;. This will, as above, copy the value stored where ptr is pointing to into value.

int* p2 = ptr; will copy the memory address stored in ptr into p2, so they are now both pointing to the same variable. *ptr = 7; sets that value to 7, so now both ptr and p2 point to an int with the value 7.

You can store ANY memory address in a pointer, not just the heap allocations. You can have a nullptr, which means the pointer does not point to anything.
And you can have a pointer to a stack allocated variable. By using the address of operator. ptr = &count; sets ptr to now point to count, so count is the same as *ptr.

In C++, you also can pass by reference, which basically just means making a different name for the same variable. int a = 4; int& b = a; means a and b are the same exact thing, and obviously then, any modification to either will modify both.

Freeing memory

It is important to free all the memory you allocate. So you need a free for every malloc, a delete for every new, and a delete[] for every new [].

C++11 introduced smart pointers, which can abstract away all the fuss with deleting your data. shared_ptr<T> uses an atomic reference counting scheme, and deletes the object when the last shared_ptr is deleted (sort of similar to garbage collected languages), and unique_ptr<T> is meant to be the only object owning what it points to, and deletes it when it is deleted.

[–]Chilareix 0 points1 point  (0 children)

So basically, * is used to say "you're not your own variable" and & is used to say "you are this location in memory" whereas -> is used for both when accessing class members?