Pointers in C ARENT HARD | Getting Started with C Pointers in 2021
Vložit
- čas přidán 5. 09. 2024
- In this video, I teach you how to write C code that makes use of pointers. Pointers aren't scary at all if you understand the fundamentals! In this video, we make pointers easy with a few diagrams and some toy code.
Learn how pointers work in C in no time! Join us on Discord! / discord
Great vid but for me when learning c pointers were easy to understand at first but hard to use.
For me the confusing thing in c pointers is that you declare a pointer with a * but then you deference (get the value not address) with a *. The address return requires just the Pointer variable name without any additional characters. However with normal variables you get value from the name and address with an ampersand. Declaration is also without a special character. You also can’t confuse Int pointers with chars and so on.
On top of that you throw in double de refs, pointers to structures, pointers to [0] elements in arrays etc.
The end result for a beginner is that the syntax and cast requirements are confusing, counterintuitive and difficult. It is not therefore correct to say it’s easy….for the beginner it isn’t. It becomes somewhat easier w practice.
For such a beautifully crafted programming language I am often surprised its initial creators didn’t choose a different symbol for declaring pointers that could also be used to indicate in code a pointer to an address. It would make understanding c code w a lot of pointers much easier.
The * in declaration is not a special “declare a pointer” operator. It is one and the same operator used when dereferencing a pointer- the indirection operator.
Delving into the c compiler syntax and corresponding assembly logic will help you grasp this.
Thank you! This is my biggest gripe with C, and what I think the sole reason why "nobody understands pointers". I learned 6502 assembly before even looking at C and I understand what pointers are - and yet I STILL find C's pointer syntax so incredibly obtuse that I still can't remember off the top of my head how to cast a pointer to a specific memory address. (*(volatile unsigned short)*0x04000130) or something like that. (If you know what hardware this is for then kudos to you)
@Drygord Spellweaver For something that isn't a "declare a pointer symbol" it sure acts like it. It's easier to explain it that way, and I think that's what leads to a lot of the confusion.
@@drygordspellweaver8761 Could you recommend some good source of information for the correspondence of C compiler syntax to the ASM logic?
I understand the basic principle but something more specific yet easy enough to understand about this topic would be interesting to delve into.
Big topic in 8 minutes? This is magic
Hey great video. Now the question is: How would i use this in my program? When would i use it? I would love a real practical example of using pointers. Maybe point (pun intended) me in the right direction for further reading/learning?
Usually you will be passing pointers to memory (structs) where you want the receiver to access the same memory, that is, without making a complete copy. That way, the receiver is able to modify the contents of the memory as a side effect.
You may want to learn about "pass by reference" vs "pass by value".
@@blizzy78 thanks for the info, ill read in to this
What makes pointers good is that they're the "great equalizer", in that regardless of the type of data they point to, an absolute memory address is the same size. So let's say you want to create an array of your favorite movies, e.g. {"Avengers", "Shrek 2", "Space Jam",...}
Now you'll notice none of these strings are the same length. Computers have a MUCH easier time indexing an array when each row is the same length.
So it's much easier to create an array of pointers to those strings instead. That way each row is the same number of bytes and to increment to the "next" string in the array the CPU doesn't need to know the length of each string.
@@williamdrum9899 great explanation! For ints its obvious cause they are fixed size so storing pointers in array makes Perfect sense for data type that size can vary
@@zandark88 I started with 6502 Assembly where you often literally learn pointers by accident. LDA #3 will load the A register with the constant 3, but if you type LDA 3 you load the A register with the contents of memory address $0003
Thanks again L^3!!!
The pointers concept at first was hard for me grasp, but after watching your 8 minute video several times and banging away at multiple iterations, your lesson sunk in.
I recently discovered your channel and have been having fun with the RPi, ASM & C content. I just took delivery on a few Picos, so I'll be hitting up that playlist shortly. I'll be checking out Discord and Twitch.
that line "Outside of the declaration", yes that was my suspicion, why does nobody else on YT or the first 10 google results say it like that. These damn search engines and algorithms prevent you from getting to a person that can actually explain things to you. I have been following for a long time and have missed this video. Good things are said here and the example is rather clear. Please, do this more.
Awesome video, dude! I write JavaScript and started to dip my toes in Objective-C, so this helps me out a lot! Very well explained.
I don't want to be that guy, but why objective c? Are you coding for an old mac or something? I would believe that any other c variant would be a more pleasant experience, would it not?
@@Solid_Fuel It's all good! Very good question! Basically I wanted to dip my toes in the water for iOS development to see if it's something I would enjoy doing. Between Swift and Objective-C, I decided to learn Objective-C as minimally as possible before switching over to Swift lmao. You know, kinda like learning jQuery even though it's getting more and more deprecated each day for the sake of all the legacy code that still uses it. It's actually a pretty cool language, though! The history of it especially!
Great to hear!
PS: i love your channel name AND the "low level" learning concepts ! this is hardly seen anywhere else these days. Often its been stopped after the top two levels, rather than showing every level down into the dirt.
Brilliant way of teaching
Thanks for this grt vdo it helped a lot.
But the confusion I have is if we write a program how are the values changed in before assignment and after assignment.
ro thankyou for these best c explanation so far for me
I totally get what pointers are. However, I don't see why they would be used, or what makes them useful?
Here's an example: Let's say you wanted to make an array of your favorite movies. (Please forgive the bad syntax, I'm typing this on my phone and C isn't my best language). It might look something like this:
{"Space Jam", "Infinity War", "Shrek",...}
Problem is, none of these are the same length, so in order to index this array you'd need to know the length of each string. So the better way is to create the strings elsewhere and then create an array of pointers to said strings:
char foo = "Space Jam"
char bar = "Infinity War"
char baz = "Shrek"
The array would be
{&foo, &bar, &baz}
Each element of this array would be the same size regardless of how long the string is, so you don't actually need to know the length of each string to index the array.
Whats foo bar and the other in here?
@@williamdrum9899 I was coming from other languages like JS and Go, where memory management has never been a thought in my mind. It never occurred to me that an array is 1 large continguous memory space and not actually separate spaces for each element, and by indexing you meant how to find the next item in the array, but after re-reading your post 9 months later I totally get it now.
@@gngn2973 Glad I could help!
@@ivanmartincampoy they're just variable names that are commonly used in textbook examples, they don't really mean anything. I could have called them "movie0" "movie1" "movie2"
brother its been two years but still I''m using yashavant let us 15th edition but the thing is it makes concepts unnecessarily hard by saying a lot of words while delivering nothing but yours was practical both in its theory and the practical syantax of it thank you for teaching me.
i think i understand what you demonstrated here. Thank you for that! BUT since im not an experienced C programmer i lack the experience i seem to need, to understand WHY pointers and dereferences are so useful in C. what is the application of "pointers". what makes them so useful ? i mean... ASM doesnt have "pointers", nor JAVA n such, right ? why C and what are they often used for ? im still somewhat "in war" with pointers concept and i dont know why :(
Me too, I need to see an application and to be shown why this is useful !
Pointers exist in Java, but their use is hidden behind the runtime java, also if by ASM, you mean Assembly languages then they have pointers too and they use them a lot, as to what use there is for pointers, they are REALLY useful for a lot of things, but if you just want an exemple :
imagine that in your program you allocate an object that has a 1Gb size, and imagine u have to manipulate it and pass it to multiple functions in your program, without pointers u would have to copy all the data everytime u want to pass it, get the result of the function and pass it to the next one, i think u can see the problem here, 1Gb is a lot to copy everytime, imagine in a program which calls the functions many times / seconds, it would be disastrous, with pointers everything is solved, u don't copy anything u pass the adress of the object which is small (only 4 or 8 bytes) and then every one of your functions know where to find your object, they can read from it or modify it in place
(sorry for my english, not a native speaker lol)
@Celtic Guardian you're welcome
I assure you that ASM does indeed have pointers, and they're used heavily. If you've ever made a lookup table, or used LDIR/REP MOVSB/etc those are pointers. Indexing an array? Pointers. LDA ($??),y? Pointers.
@@williamdrum9899 pointers in ASM work different, don't they?! In c an int pointer if incremented adds length of word bytes to the address. In ASM only +1 unless you use add 4 or so. Right? You maybe call both pointers , but they work different it seems
Excellent explanation. Keep dropping the great content.
Omg it finally makes sense. Thank you so much!!!!
Nice explanation i will share to my friends.
I have a question
Suppose we have: int *x = 4
What will be the value of *x? (not x)
int *x = 4 syntactically means your creating an int pointer who’s value (so therefore, who’s address) is 4. *x is whatever value is at address 4, which will likely crash your program
Thank you so much. No more mystery. No more confusion. 😀😀😀😀
You’re welcome 😊
Finally, I understand it.
Thanks a lot.
Thanks I thought this explained what pointers are pretty well. My question though is why? Why use a pointer, why have double pointers? Is there some advantage or neccessity to them? I'm sure I'll get to that soon though
There is. If you have an array of strings, and you want to get to the next string in the array, it's much easier to create an array of pointers to each string, so that it doesn't matter if each string in the array is a different length.
this is exactly what I needed.
thank you very much :)
Thanks a lot
Great video, keep up the good work!!
Thanks, will do!
Thank you!
Like! Could you please show the kind of problems that pointers can solve?
An example: in main{} you declare an array: {1,2,3,4,5...on to 1000} . next you want to create a function outside of main{} that sums those values. You have a choice here: you can have the compiler copy each value of your array into your function then sum all of it, which takes up a lot of memory, or you can pass a pointer to the first element of the array declared in main{} as an argument then have your sum function sum up the values **that are already in memory**. the second method is much less memory intenstive; therefore, you see this "modify by reference" idea used all the time in C.
@@audiodiwhy2195 I presume also saving the time it takes to copy the data, and therefor explaining why C is so much faster?
@@jackgerberuae Yes! But also, it is only as fast as the developer allows it to be.
Problem: You have a "jagged" array where each entry is of unequal size, such as an array of strings.
Solution: Instead of directly creating an array of strings, create an array of pointers to those strings. Now the CPU can easily traverse the array without needing to know the length of each string.
So great ❤
Good job man
So if you have a pointer pointing to a pointer pointing to a pointer; would it be ***my_d_ptr = &mypointer ????
Ok I get it, thanks
Nicee
4:56 can you please say why gcc, why not clang?
Thank You
You're welcome
what if x value was set to 0x7fff0004 and the address is also 0x7fff0004 (is there any datatype that makes it possible .).. does this cause any problems later in the code like if we call the value and it refers its address and it drops as a pointer and things turn to infinity..
That's not a problem at all. You can store a number that equals its own address and there will be no issues. For example if we did a hexdump at 7fff0004 we would see the following (assuming a little endian architecture):
The byte at 7fff0004 equals 04
The byte at 7fff0005 equals 00
The byte at 7fff0006 equals FF
The byte at 7fff0007 equals 7F
THANKS! another known unknown demystified ..
You bet!
So, I understand the pointers(i think) my real question is... why do you need to say that is a double pointer(**)? declaring that is a pointer should be enough?
C makes you declare a type to go with a pointer, but in reality pointers are typeless. The CPU has no actual way of knowing what a pointer points to (I was going to say "until it's dereferenced" but it really doesn't even know then.) The double pointer tells C that "if you dereference this pointer that's not the underlying data I want to operate on".
@@williamdrum9899 Thanks for your explanation! I was wondering the same, and actually why even the the first-stage pointer (what might be the right word?) needs to be explicitly declares as a pointer variable, if after all the pointer is just a value in the variable which happens to be an address.
But your explanation made some sense, so did I understand right that the declaration as a pointer variable tells the compiler to use the declared data type to interpret not the content of pointer variable, but the content in the dereferenced address? And with double pointer, use the data type to interpret the value in the final dereferenced address?
@@TheSimoc Yes, I think you understand correctly.
would *** be tripple or would that also be **
I kind of got something but actually it was too fast for me so I'm confused
You know you can build C executables directly in sublime
How ? make a video.
why does the value of address keep changing in memory?
The value of address keeps changing because it's dynamically allocated. He defines the 1st variable, x, and doesn't tell C where to store it, just to store it. Thus, the C compiler grabs the 1st available memory it has access to, depending on the OS. So, that's why it changes whenever he runs the program.
@@stefsmurf thank you for explaining
Typically variables are not understood as a plain old memory address. There are many different kinds of variables, but local variables that live inside of a function scope exist as an offset rather than as a memory address. so you wouldnt be saying "x is stored at 0x7fff0004" you would be saying "x is stored at ebp-4". however, if you were to get &x, it would give you x's memory address, not its offset.
Pointers aren't hard. Achieving dynamic allocation is.
That's why I like working with classic game consoles (the ones that literally do nothing without a game in them). "Here's 64K of RAM, go nuts"
1 like for using sublime
Pointers are not hard to get right, so much as they are easy to _get wrong._