Fixed and Variable Length Arrays in C and C++

Поділитися
Вставка
  • Опубліковано 30 лип 2024
  • Patreon ➤ / jacobsorber
    Courses ➤ jacobsorber.thinkific.com
    Website ➤ www.jacobsorber.com
    ---
    Fixed and Variable Length Arrays in C and C++ // Beginners to C and C++ are often confused with arrays and the different ways we create them. This video shows you how to create both static and dynamic arrays. I show you how to use malloc and free, as well as the new and delete operators to create different-lengthed arrays, and how to use realloc to resize an array if it needs to get bigger or smaller. I also show you how to pass arrays as arguments to functions and how to write functions that can handle arrays of variable lengths. Have fun. I hope this helps.
    Related Videos:
    • Arrays, Pointers, and ...
    ***
    Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
    About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
    More about me and what I do:
    www.jacobsorber.com
    people.cs.clemson.edu/~jsorber/
    persist.cs.clemson.edu/
    To Support the Channel:
    + like, subscribe, spread the word
    + contribute via Patreon --- [ / jacobsorber ]
    Source code is also available to Patreon supporters. --- [jsorber-youtube-source.heroku...]

КОМЕНТАРІ • 123

  • @nourway3639
    @nourway3639 3 роки тому +87

    can you make a series about linux kernel development . BTW very good content already

    • @soumyadipsaha8904
      @soumyadipsaha8904 3 роки тому +5

      yes plz make one series about linux kernel development

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

      Yeah that's a good point. Really appreciate.

    • @Ryan-mn6xs
      @Ryan-mn6xs 3 роки тому

      This would be great!

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

      that would be aswell as awesome as it is usefull :) i love it. Windows Driver Development is interesting too thouh

    • @JacobSorber
      @JacobSorber  3 роки тому +38

      Yeah, at some point, I'm sure we'll get into the kernel. Are there specific in-kernel topics you would want to hear about?

  • @NiX_ARG
    @NiX_ARG 3 роки тому +22

    A cool hack with some limitations if you dont want to keep track of dynamic array sizes yourself is to set the last element of the array to an invalid one (like -1, INT_MAX, NULL,..) and then use a while loop to get the size

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

      That's exactly how zero terminated string in C work.
      A string in C is no other than an array of characters where the zero indicates the end of the array (dats).

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

      what an amazing way to shoot your self in the foot. There is a reason all modern languages are moving away from sentinel termination. To any beginner reading this dont EVER do that.

  • @shawnmelody8346
    @shawnmelody8346 2 роки тому +5

    So glad I found your channel. Clear and understandable English, no blaring music in the background, or the opposite (like watching a silent movie in
    super-speed...lol 😁). Very instructional, informative and engaging to say the least! Kudos! Thanks for the awesome work you put into such a great channel.

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

    1:30 yes, please make a video to show how to store different types of elements together in a compact and efficient form in Cpp. It would be great to see how you do it.

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

    I've recently revisited C/C++ having not really done much with it in about 15 years. Your videos have really helped strengthen my fundamentals and brush off a lot of the cobwebs. Thanks for that!
    If you decide to cover some C++ topics, I'd love to see some stuff on the nitty gritty of streams. I can implement something using them but always felt that I've got a bit of a blind spot with what's going on under the hood.

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

    Thanks, outstanding video! Especially the comparison with cpp code adds extra educational value.

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

    Instead of keeping track of sizes of arrays manually, I like to define macros for when I need them. In the print example:
    #include
    #define LEN(arr) sizeof(arr) / sizeof(*arr)
    #define PRINT_ARR(arr) printarray(arr, LEN(arr))
    void printarray(int arr[], int size) {
    for (int i = 0; i < size; ++i) printf("%d ", arr[i]);
    putchar('
    ');
    }
    int main(void) {
    int myArray[5] = {3, 1, 4, 1, 5};
    PRINT_ARR(myArray);
    return 0;
    }

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

      I always wondered but why aren't those simple yet useful macro not in the stdlib?

  • @sumdim6427
    @sumdim6427 3 роки тому +1

    Hi! Jacob🙂. I learned a lot from your channel. I was having trouble about learning and using variable argument list when implementing printf for school project. After watched your video(the video is just about 4~5 minutes long, simple and straight to the point), Things came clear to me. I realized It is actually not that complicated.
    Thanks for the helpful content!
    I think It would be really helpful also if you can make a video about writing unit test, what general, edge case we should be careful for, (this may sound broad), and tool we can use, etc...

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

    Your videos provide a lot of clear information. I've learnt a lot from your content. It's really amazing.
    Thank You so much.

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

    Thank you for this!

  • @3dnacho
    @3dnacho 3 роки тому +1

    Thanks for the good content. I wold love a video about these tricks to store diferent types in a array in C.

  • @sukivirus
    @sukivirus 3 роки тому +1

    Loved it. I would love to learn compiler/interpreter design. May be create scripting language for my programs in C using C. I just love the way you try things in C. I am enjoying it :)

  • @pavolkucerak6011
    @pavolkucerak6011 10 місяців тому

    Jacob, thank You for this and for other videos.

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

    This guy deserves A RAISE!

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

    Great content! Thanks

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

    Just found your videos, and OMG thank you so much I have learned so much, your videos are so informative and the knowledge is great.

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

      Thanks, Adrian. Glad I could help.

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

    Good stuff, thank you! Subscribed. I find that if I feel like doing some low level stuff, C fits my style much better than C++. It's simple and to the point. Modern c++ is so cumbersome and it puts me off. Otherwise, I'm happy with C#(-:

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

    Great video! Love the t-shirt. :) Thanks for posting!

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

    One of the reasons not to mix new/free and *alloc/delete is because of class/struct constructors/destructors. If you have an array of, or a single of, any intrinsic type, it would likely work, but still do not do it.

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

    Since you mentioned older C standards didn't allow it, is there any overhead (apart from fetching from memory) associated with dynamically allocating an array with the value stored in an integer variable?

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

    5:18 Why did it take so long to launch? Is it because osx is sending the hash to apple or just the terminal emulator taking its time?

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

    Wouldn't myarray[5] in the function parameter be cast to just be a pointer to an int?

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

    I would love to see a video on smart pointers in C++. Specifically how they work under the hood and what are some good use cases for when we should be using smart pointers and when not to use smart pointers. Also if possible, can you do a video on memory checking tools like valgrind? Great videos by the way!

  • @michaelkotthaus7120
    @michaelkotthaus7120 3 роки тому +1

    At 11:26, you can also use the function calloc for zero-initialized dynamic memory.

  • @user-yo3zq4hz8c
    @user-yo3zq4hz8c 5 місяців тому

    Is there a way we could find length of this dynamically created array (using malloc) with the help of sizeof ? What is the correct syntax for using it ?

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

    How would I go about creating a large array that uses the input and a loop to initialize the variables, while not having to initiialize my entire array.
    For example: My array can contain 30 integers, but at some point I decide to only initialize 10 of them. How can I do this without having to just change the size of my array.

  • @belesiu
    @belesiu 3 роки тому +1

    Excellent videos - thanks! Can you expand a bit on the pros/cons of using const int vs #define for magic numbers?

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

      Sure. I'll add that to the list. Thanks.

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

    We want more c++ videos ❤️

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

    I really like your videos. It helped me a lot. Please can u make tutorial videos for nasm?. Just for beginner!
    I have tried to see it but i didn't understand anything

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

    Hi Jacob, are you planning to do some C++ tutorials?

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

    Jacob, thank you for your insightful videos. I’m not certain, but I think we are both members of the same church (I can sorta just tell).
    Could you make a video covering how variable-length arrays can be unsafe because they can overrun the stack? Also, it might be good to point out that the compiler will need to use dynamic sizing of stack frames rather than static sizing if you use VLAs, which can lead to some performance issues under some rare circumstances.

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

      You're welcome. So, I'm giving off a church-y vibe, eh? 😀 And, thanks for the topic ideas. I'll add them to the list and see if I can work them into a future video. Thanks.

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

    It would be great to have video series about using standard C implementation of multithreading, with threads.h header, not pthreads. What do you think about it? :)

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

      I've thought about this - still thinking about this. Both threads.h and pthreads are standard, just different standards. I personally prefer the pthreads API, but does seem like a good topic to break down. I'll put it on the list. Thanks.

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

    in 18:58 , when you made a micro-program which initliaze an array with the number of arguments passed , you could just use sizeof() instead of including a new library , calling a new function strlen()... ( char is 1byte == 1 argument )

  • @hirokjyotinath2246
    @hirokjyotinath2246 3 роки тому +1

    Sir please make more videos lectures
    You are great thank you sir

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

      Making them as fast as I can. 😀 Glad you're enjoying the channel.

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

      You are the best teacher

  • @fordfactor
    @fordfactor 3 роки тому +1

    Which C standard introduced the ability to size an array with a variable?

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

    can you please talk about 2d arrays ? from a C programmer prospective ( including pointers , addresses .. )

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

    Hi Jacob great video, I have a few questions =>
    1. VLA's can cause stackoverflow and therefore be used as an exploit right?
    2. How is VLA implemented by the compiler? Because till run-time we do not know the size, how will the compiler create offsets for other variables on stack?
    Thanks

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

      Hi Sahil, This might help illustrate how the compiler works godbolt.org/

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

      It's not required, that C99 VLAs are allocated on the Stack. GCC does this, but you have to look into it on a compiler-to-compiler basis. The easiest approach is probably just putting VLAs at the end of the allocations, so you don't mess with the other variables. If you eg have multiple and hence can't use that strategy a compiler may store pointers onto a fixed location on the stack and then allocate everything at the end. However this is once again up to the implementation

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

      First of all. VLA is about typing. The essence of VLA is this `typedef int type[n]`, not `int array[n]`. The main purpose of VLAs was simplification of handling multidimensional arrays. VLAs can be allocated on stack `int array[n]` but also can be allocated on heap by using a pointer to VLA array `int (*array)[n] = malloc(sizeof *array)`. For automatic object try to avoid suing VLA, expecially if the size if coming from a non-sanitized input.

  • @aymankurdi6807
    @aymankurdi6807 3 роки тому +1

    I have a difficult question, how can i ignore special keys like F1 or F2 .... when getting input from user in c lang, i solved this problem by checking for escape char '\e' then flushing the rest of the chars cheking for numbers 81 82 83 126 and 72 to stop the loop.
    but i am not sure if that is the optimal solution.

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

      no expert here, but maybe his video on signal handling will help?

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

      @@SoulSukkur my understanding is that signals are caught by the kernal and sent to the process and you can change basic behavior, but special keys like F keys are buffered to stdin as a series of chars, for example F7 sends 3 ascii chars ^ [QO so you will get garbage in stdin and have to check for the escape char then clear the rest which is a headache.

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

    What IDE/environment is this?

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

    I was hoping you would talk about 2d variable length arrays. I'm having a hard time initializing and using them, specifically a 2d VLA of structs.

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

    What is differential between C11 and C99?

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

    I have a question:
    For example I have a struct named Student and declare: struct Student student[100]; (or *student[100]?)
    Can I have different sizes for: char student[0].name[?] ?
    Essentially I want to have a larger array, if the students name is longer. Is this possible? Or do I just have to find the maximum length and then waste some space?

    • @briannormant3622
      @briannormant3622 Рік тому +2

      I guess that by this time you founded your answer but if some people are wondering I think the best way would be to store a pointer to the pointer of the string like this:
      struct Student {
      char** name,
      //Other data
      }.
      Set it using memcpy() and don't forget to free it.
      Get it by *student[0].name

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

    wait, if those static arrays are still on the stack, how it gonna know the stack size at runtime then u use int runtime_array[argc]? And if it ISN'T on the stack, does one have to dealloc it manually? Feels like some kind of witchcraft is going on

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

      I had the same question looked it up and found "Variable-length array" on wiki. They say :
      The GNU C Compiler allocates memory for VLAs with "automatic storage duration" on the stack.[4] This is the faster and more straightforward option compared to heap-allocation, and is used by most compilers.
      Just putting this here if other people happen to see this.

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

    why we cann't assign array for an other array directly?

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

    11:40 memset is not gonna work correctly if you want something else than zeroes, because it fills one byte at time whereas int is likely 4 bytes in size.

  • @R4ngeR4pidz
    @R4ngeR4pidz 3 роки тому +1

    I was hoping to learn the difference in performance, efficiency, or just what goes on under the hood when using a variable length array versus a fixed size array

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

      I guess I need to make a second video on arrays. 😀
      On the performance front, there's probably not that much to say, except that malloc, realloc, free, new, delete will incur a small penalty (depends on your allocator). Once allocated, the different options should all perform roughly the same. We could look at how allocators work under the hood.

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

      @@JacobSorber Hi Jacob can we see how alloca works? Thanks

  • @user-it8yh8tu7d
    @user-it8yh8tu7d Місяць тому

    Why are smartpointers not possible in strict C?

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

    so a variable length array is a dynamic array under the hood?

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

    Can U ref to or create a video on handling charsets like utf8 utf16 in C

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

      Yeah, I've been wanting do to a unicode video. Just haven't yet found time to put it together.

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

      @@JacobSorber Do care to point me once U do it... Thanks

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

    please make a video on vectors

  • @HimanshuSharma-sd5gk
    @HimanshuSharma-sd5gk 3 роки тому

    Plz plz answer this question sir..
    For passing multidimentional array to function how valid is to use
    void function(int x, int y, int array[x][y]);
    This worked fine on my system.
    I am himanshu sharma from india

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

      It is a very valid usage of VLA types. In the current C17 standard, VLAs are optional and some implementation like crappy MSVC compiler does not support it. However, upcoming C23 standard *will* make VLA types mandatory again. Only automatic objects of VLA type will stay optional. Your code is going to be a perfectly portable C23 code.

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

    I'm a begginer in C/C++, can someone explain me how to resize an array/pointer size at run time? E.g. I create an char array/pointer with size 10 and I ask the user their name, let say their answer is bigger than 10, how can I avoid an error/overflow?

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

      use realloc function if you created array using malloc or calloc

  • @neillunavat
    @neillunavat 3 роки тому +1

    how to return dynamic arrays from functions in C? (no resources found for this) (beginner programmer in C here...)

    • @not.harshit
      @not.harshit 3 роки тому

      Sorry to see that nobody answered you yet. AFAIK you can only return a pointer to the dynamically allocated array.
      Note that C only allows you to return either primitive data types{char, int, float, …} or pointers to complex data types{ struct, union, …}

    • @neillunavat
      @neillunavat 3 роки тому +1

      @@not.harshit yep. Thx for reply but sry i figured it out 😁 still, know that this helped me a lot.

  • @user-ot5xm7ye1v
    @user-ot5xm7ye1v 10 місяців тому

    Супер

  • @axlslak
    @axlslak 3 роки тому +1

    hahaha.... i love you t-shirt teach :)

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

    when you use realloc, the old 15 integers are deleted and the system allocate 20 new integers somewhere in the memory space

  • @BrunoSilva-rr6cb
    @BrunoSilva-rr6cb 3 роки тому

    What happens when you reallocate to a smaller size?

    • @JacobSorber
      @JacobSorber  3 роки тому +1

      That's up to the allocator. All you can count on is that it will give you a pointer to a block of memory that has at last the new smaller size bytes of space in it. In practice, it could just give you back your original pointer, since the original block was already big enough to hold the smaller size.

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

    Is c++ relevant for embedded system programming on small controllers? If so, then yes, let’s learn vectors and containers!

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

    I am using gcc 9.3.0 on WSL to compile on PC. When I attempt to use const to set the size of an array I get a "variable-sized object may not be initialised" error.
    I have tried gcc 11.1.0 on arch Linux with the same result. And, while I'm no make expert, using what was on screen I cobbled together a makefile that works in all instances except when I try to initialise an array using a const int.
    #define works as expected as does using an enum (suggested on forums elsewhere).
    With two alternative solutions, from a purely functional POV, I know I need not worry about the issue. However, I would like to know why this is happening.
    My initial suspicion, based on forum posts, was this represents a bug fix from a previous version of gcc as, I kept reading, consts in C are not truly immutable; but further reading has seemed to suggest C99 and onward are more flexible and should allow the use of const (or sometimes even just normal ints) and #define is actually the old methodology (although running with the -std=c99 flag or just invoking c99 rather than gcc yield the same results).
    It seems like I am doing something wrong. Or, at the very least have failed to understand something. And, I'm just looking for someone to set me straight.
    *EDIT* will also compile if I declare the array without assigning any values.

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

      This code is not correct, and won't compile in any standard gcc compiler, you can't use a variable as array size in C when you initialize it, VLA's are valid in C, but only if just for declaration, const is tricky on C, you should use #define ARRAY_LENGTH 5 for a propper constant, my guess is that this code, being ran on mac OS is using gcc as an alias of clang whose extensions allow for non-standard constant folding. If you want to learn solid C go elsewhere.

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

      @@anastaciu hmm, that is interesting. It does definitely compile with clang (I checked after other research). It's strange to me the number of people teaching who don't seem to know about this (I ended up here after starting somewhere else with the same problem). And, the number of people who don't seem to care about the error. Thank you for taking the time to provide me with this answer. The whole thing has been bugging me most of the day.
      Probably not the best place to ask, but do you happen to know anywhere that is good for learning solid C?

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

    As a quick note VLA's aren't mandated since c11.

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

      It's worth checking that the C and C++ standards haven't always been in sync on this issue. So, if portability with a particular standard is important, you should double check the one you're coding against.

    • @oj0024
      @oj0024 3 роки тому +1

      @@JacobSorber You can check for VLA's using __STDC_NO_VLA__.

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

    C++? what is this malarkey?

  • @anshul493
    @anshul493 3 роки тому +1

    hey:
    to get the sizeof array: do
    ```{c}
    int length=sizeof(array)/sizeof(array[0]);
    ```

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

      well,that sizeof(array) is going to return sizeof of that pointer stuff...
      and would work only for static arrays..

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

    Hi dear professor, do you have any C++ 20 tutorials????? Can make C++ tutorials PlesssssssssssssssssssZZZZZZZZZZ!!!!

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

    3:06 "It's important to note for beginners that we do start with zero, if you're wondering about why that is, I do have a video that talks about that, I'll put a link in the description".
    Link is not present in the description.

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

      Oops. Sorry about that. Link is now in the description. Thanks for pointing that out.

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

    careful with realloc, this might cause memory leak if realloc failed. if realloc fails it returns null so now you lost a reference to the older pointer if you do p = realloc(p, newsize).

  • @KamiKagutsuchi
    @KamiKagutsuchi 3 роки тому +1

    you should have mentioned std::array when talking about C++

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

      And that it is possible to use the sizeof() operator on a fixed size size array parameter when it is passed by reference.

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

    7:00 this is not gonna work, for VLA limitation reasons.
    It needs to be changed to *#define** ARRAY_LENGTH 5*

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

    8:28 "pointers and arrays are almost exactly the same thing"
    This is a blatant lie.
    A pointer is a block of data containing an address. It will be size 1 byte for 8 bit machines, 4 bytes for 32 bit, 8 bytes for 64 bit, etc.
    An array is a block of data of any type and can be any size.
    It is true that an array names are similar to a pointer, and array syntax is similar to pointer arithmetic, but pointers and arrays are vastly different.
    If someone wants to make a video on how to dereference a pointer to a pointer of 3d pointers using pointer syntax, array me to it.

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

    Arrays? No thanks. I prefer a raise (I don't get paid enough