How to return and pass a struct to a function

Поділитися
Вставка
  • Опубліковано 30 вер 2024

КОМЕНТАРІ • 73

  • @giuliomoscatoba8905
    @giuliomoscatoba8905 3 роки тому +16

    I really hope you get more subscribers man, your video are by far the best when it comes to c programming.

  • @ChildishBerbino
    @ChildishBerbino 5 років тому +24

    Mastering C feels like learning some sort of arcane magic...

  • @drcl7429
    @drcl7429 2 роки тому +6

    Finally understand why so many library functions ask for a pointer for result instead of using a return value.

  • @whenthethebeansstrikeback6728
    @whenthethebeansstrikeback6728 4 роки тому +15

    It took me a while, but this has got to be the best video on this topic!

  • @ramelgov7891
    @ramelgov7891 2 роки тому +10

    What a fantastic lecturer! Always straight to the point (and to the subtlest and most important ones!). Your explanations are always cleanly compiled.

    • @CodeVault
      @CodeVault  2 роки тому +2

      Thank you! I try my best. These types of comments motivate me to keep going

  • @yabool2001
    @yabool2001 3 роки тому +10

    This is a really worthwhile and best video on returning the structs!

  • @Sarahhh123
    @Sarahhh123 3 роки тому +8

    Thank you so much for this, you are truly great!

  • @OZtheVillain
    @OZtheVillain 3 роки тому +10

    This was such a great video, I really learned a lot. Thank you so much!

  • @sanjoy2227
    @sanjoy2227 3 роки тому +2

    Thanks bro.... you just cleared my confusion about C++ and C# about the default function calling type

  • @7GIGEO7
    @7GIGEO7 3 роки тому +4

    Excellent and on point explanation. Thank you.

  • @kisiki_kt_na_lage
    @kisiki_kt_na_lage 4 роки тому +3

    Thank you so much for this video

  • @ArkFreestyle
    @ArkFreestyle 3 роки тому +3

    Thank you! Super helpful.

  • @figiegi4911
    @figiegi4911 3 роки тому +2

    thank you man
    Keep up the good work!!

  • @StartBuilding
    @StartBuilding 2 роки тому +1

    CAN WE GET A TUTORIAL ON BUILDING A PROJECT WITH C... SEEMS I HAVE DONE ENOUGH ON THE LEARNING ASPECT LEFT WITH THE APPLICATION

  • @incognito8336
    @incognito8336 4 місяці тому

    That was simple amazing. Step by step, explaining the thought process at each one of them, until reaching the perfect code... Thanks!!

  • @soniablanche5672
    @soniablanche5672 8 місяців тому

    small struct like point and any kind of pointer wrapper I would pass them by value

  • @fabiovsroque
    @fabiovsroque 8 місяців тому

    Hi, Nice vídeo, Very easy to understand, thank you.

  • @dabunnisher29
    @dabunnisher29 2 місяці тому

    Fantastic videos. Your instruction is very good.

  • @joaquingasparalison737
    @joaquingasparalison737 Рік тому

    Great video mate! Rewards from Argentina.

  • @naboulsikhalid7763
    @naboulsikhalid7763 5 місяців тому

    as you say (AMAZING). thank you

  • @RacecarJ0hnny
    @RacecarJ0hnny Рік тому

    I changed my mind you are actually quite cute

  • @helyadadkhah7059
    @helyadadkhah7059 Рік тому

    clear explanations, thanks!

  • @patrickjaeger9714
    @patrickjaeger9714 Місяць тому

    at 13:00 you mention that java ‘already passes by reference’; as the smart way does in c, shown by you as the 3rd way. however i’m missing a finer distinction between reference, pointer and address, e.g. should reference and pointer be equaled, are they working the same? to me structs and arrays in c are addresses.

    • @CodeVault
      @CodeVault  15 днів тому

      There is either "pass by reference" or "pass by value". In C... everything is passed by value. Pointers hold addresses but, when you call a function, you actually pass the value of that pointer to that function (the value, in this case, being an address). When passing a struct, the program makes a copy of it on the stack of the function called. When passing an array you pass by value the address to the first element.
      In higher level languages (which are garbage collected), objects and arrays are passed by reference instead and the compiler does this dereference operation for you. Usually just primitives (int, bool, char etc.) are passed by value because it's cheaper to simply copy the value and send it to the function

  • @AshtonWolfwood
    @AshtonWolfwood Рік тому

    So is the malloc only required for things where we dont know the size of at compile time? For example lists of objects? Everything else could be done by using the stack allocation?

    • @CodeVault
      @CodeVault  Рік тому

      Yes, most of what you need can be done on the stack. There's a stack memory limit of 1MB (but it depends). So also, if you need a variable that uses more than 1 MB you would need to use malloc for it

  • @ejsafara456
    @ejsafara456 Рік тому

    thank you, helped a lot! :D

  • @Jashodhan
    @Jashodhan 7 місяців тому

    I am not able to understand some of your videos. What should i do. I think they are some high level.

    • @CodeVault
      @CodeVault  5 місяців тому +1

      Exercise on your own. Take the code I am explaining and try to change it little by little. Also, research the documentation thoroughly

  • @juanmamani2110
    @juanmamani2110 Рік тому

    I'm from the 80's and your video is really awesome how you expose through levels the right use of pointers in a "healthly" way. Thanks for sharing!!.

  • @kcvinu
    @kcvinu Рік тому

    I want to return the pointer of a dynamically allocated struct from a function. But my program is a gui library. The pointer I want ti return is a TreeNode struct for a TreeView. So I want to keep those pointers in a list and when the TreeView get destroyed, I want to check the status of that pointers and want to free them one by one. Is it possible ? This is to avoid the user from the burden of freeing the tree nodes..

    • @CodeVault
      @CodeVault  Рік тому +1

      A good practice is to leave the resposibility of deallocation to whoever allocated that data. But, if you want to implement it that way you can always assign NULL to pointers that have been deallocated. Although you might need to pass a double pointer to your function. Here is a video related to the topic: code-vault.net/lesson/rh1tys8m13:1603733526917

    • @kcvinu
      @kcvinu Рік тому

      @@CodeVault Thank you very much for your suggestion. I didn't think about the double pointer.

  • @vaibhavnayak6521
    @vaibhavnayak6521 2 роки тому

    bcuz of your videos i am starting to understand and like C. Thank you.

  • @OLIV3R_YT
    @OLIV3R_YT Рік тому

    Thanks ❤

  • @didiTchu
    @didiTchu 2 роки тому

    bravo!

  • @user-mj1wg5oz2b
    @user-mj1wg5oz2b Рік тому

    the fact that he doesnt look at notes or script shows me how well he knows his stuff in contrast to others

  • @יונתןאלוני-ר3פ
    @יונתןאלוני-ר3פ 2 роки тому

    You are such a good instructor! Thanks!

  • @gluraki4444
    @gluraki4444 2 роки тому

    very good vid helped quite a lot

  • @dfgw8416
    @dfgw8416 3 роки тому

    the ---> Point* getmiddlepoint has point m struct inside so struct inside struct... right???

    • @CodeVault
      @CodeVault  3 роки тому

      getMiddlePoint is just a function and m is a local variable for that function

  • @fusca14tube
    @fusca14tube 2 роки тому

    Awesome! What about declaring a "static Point" at getMiddlePoint function, and return the pointer?

    • @CodeVault
      @CodeVault  2 роки тому +1

      That would work as well

  • @Epic-so3ek
    @Epic-so3ek 3 роки тому

    I get the error incompatible types when assigning to type 'Point (aka struct Point)' from type 'int'

    • @CodeVault
      @CodeVault  3 роки тому

      Hmm, what's the code you have? You're assigning something wrong to the Point variable

  • @prathapbillgates
    @prathapbillgates 2 роки тому

    if we return structure, what exactly it will return. which means it return structure values or structure address?

    • @CodeVault
      @CodeVault  2 роки тому

      Structure values. It basically returns a copy of the structure (same as how you return a primitive like an integer)

    • @prathapbillgates
      @prathapbillgates 2 роки тому

      @@CodeVault thanks a lot. Also i have one more doubt. Inside function if we declare structure using pointers but without malloc(ex: point* m;)where it will store, either stack or data segment?

    • @CodeVault
      @CodeVault  2 роки тому

      Any variable you declare in the function is stored on the stack.
      point* m;
      Although, this variable is a pointer (an address), not the struct itself. The struct doesn't exist yet. Doing this:
      m->x = 15;
      Would throw an error. You create the struct using malloc or you could set the pointer to point to some other point struct:
      point* m;
      point n;
      m = &n;
      m is a pointer to the struct n here. You have just 1 struct in this piece of code here basically

    • @prathapbillgates
      @prathapbillgates 2 роки тому

      @@CodeVault Thanks a lot @CodeVault

  • @juanmagm
    @juanmagm 3 роки тому

    Thank you bro, very clear!! where are you from??? i'm Colombian, and way older than you!!

  • @nash494
    @nash494 2 роки тому

    How come we are able at 6:37, this works? We are trying to access a variable that got popped from the stack, for example if the function returned int*, and we tried to access that array that got allocated in the stack, we would even get a warning because we are trying to return the address of a local variable.

    • @CodeVault
      @CodeVault  2 роки тому

      It works only because I deallocated the memory right when it got free. The code essentially looked at some garbage values that just happened to still have the same value as before the deallocation in them. If you wait a while before deallocating you will either get completely random values or a segmentation fault because that part of memory is used by another process

  • @smrtfasizmu6161
    @smrtfasizmu6161 2 роки тому

    As someone who learns Java it is weird to me how structs are copied in C. It is weird to me that instances of structs aren't pointers. I don't understand what they are if they are not pointers.

    • @CodeVault
      @CodeVault  2 роки тому +1

      Well, with Java you pass around pointers all the time except for primitives. So, when passing around a struct in C it's similar to passing around a primitive (like an int) in Java. You basically pass a **copy** of that struct and not just a reference to it.

  • @prathapbillgates
    @prathapbillgates 2 роки тому

    If we check the size of the struct example: struct {char a;int b; double c;}; how the structure padding works here? Here size is 16 bytes. if 32-bit processor then 1word=4bytes, if 64-bit processor 1word=8bytes, let us consider i am working with 32-bi processor char =1bytes+ 3bytes extra for padding , int =4 bytes and double = 8bytes(4 + 4) then, size of this struct is 16bytes. suppose in this case struct{char a; int b; double c; char d;}; in this scenario how size will allocate here?

    • @CodeVault
      @CodeVault  2 роки тому

      The video is quite outdated and partially wrong. But basically the padding makes sure each member of the struct is at an address multiple of its size. So:
      a would be 1 byte at address 0 of that struct
      b would be 4 bytes at address 4 of that struct
      c would be 8 bytes at address 8 of that struct
      d would be 1 byte at address 16 of that struct
      The struct itself will be of size 24 bytes on 64-bit arch and 20 bytes on 32-bit arch
      Here's a program that you can run to test:
      #include
      #include
      typedef struct t{
      char a;
      int b;
      double c;
      char d;
      } t;
      int main(int argc, char* argv[]) {
      printf("%zu
      ", sizeof(t));
      printf("%u %u %u %u
      ", offsetof(t, a), offsetof(t, b), offsetof(t, c),>
      return 0;
      }
      For 64 bit compile: gcc -o main main.c
      For 32 bit compile: gcc -o main main.c -m32

    • @prathapbillgates
      @prathapbillgates 2 роки тому

      @@CodeVault thanks a lot

  • @megarix007
    @megarix007 2 роки тому

    thank you so much

  • @CallousCoder
    @CallousCoder 2 роки тому

    Very well explained, better than I tend to do 😅 In my old job we had interns that I always had to teach to stop returning a value like it is done in Pascal or Java.
    And I was very confused to find out that in college they didn’t learn that arguments go on the stack. That a stack pointer just moved back up when you exit and indeed if you had another thread running the stack could’ve been changed. We had that happen.
    And ironically those Java, Python and pascal people hate seeing a pointer being passed to home a result. That’s a foreign concept to them. And that’s why I am a firm proponent of at least having students code in assembly for the first semester. Even on a simple 8 bit micro doesn’t need to be very complex.
    Just to really understand how memory is used.

    • @CodeVault
      @CodeVault  2 роки тому +1

      Yeah, in my University we learned assembly in the first semester. It was incredibly helpful in understanding the rest of the languages

    • @CallousCoder
      @CallousCoder 2 роки тому

      @@CodeVault I agree, to me the knowledge of assembly really helped me understand C. It doesn’t matter what cpu you learned assembly on. The fundamentals are the same from 6502, z80, 68000 to arm and x64. It also really helps me in debugging core dumps.
      Unfortunately it’s getting rare that students get assembly here in The Netherland at least.

    • @IvanScriptsEverything
      @IvanScriptsEverything Місяць тому

      Strange. I learned python first semester, and only on the third I'm learning C and system design, followed by assembly on the fourth semester. This is dumb that new programmers aren't given the opportunity to learn memory in depth.

    • @CallousCoder
      @CallousCoder Місяць тому

      @@IvanScriptsEverything I don’t understand the order either. I do understand that they start with a higher language just to get comfortable and not immediately scare everybody away. But then you’ll need to so assembly and then C. You’ll appreciate C and that higher language all the more.
      We did pascal 1 semester and then assembly and the rest of college it was C.

  • @starfart69
    @starfart69 3 роки тому

    How about passing and returning an array of structs?

    • @CodeVault
      @CodeVault  3 роки тому

      In this video I show how you can return an array: code-vault.net/lesson/iyvrv54u8e:1603733520962

  • @hosseinzare6684
    @hosseinzare6684 2 роки тому

    Great job!