Fixed and Variable Length Arrays in C and C++

  Рет қаралды 44,580

Jacob Sorber

Jacob Sorber

Күн бұрын

Пікірлер: 125
@nourway3639
@nourway3639 3 жыл бұрын
can you make a series about linux kernel development . BTW very good content already
@soumyadipsaha8904
@soumyadipsaha8904 3 жыл бұрын
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!
@PflanzenChirurg
@PflanzenChirurg 3 жыл бұрын
that would be aswell as awesome as it is usefull :) i love it. Windows Driver Development is interesting too thouh
@JacobSorber
@JacobSorber 3 жыл бұрын
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?
@brambeer5591
@brambeer5591 3 жыл бұрын
Thanks, outstanding video! Especially the comparison with cpp code adds extra educational value.
@JacobSorber
@JacobSorber 3 жыл бұрын
Glad it was helpful!
@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.
@tannerted
@tannerted 2 жыл бұрын
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 жыл бұрын
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.
@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!
@mr.mirror1213
@mr.mirror1213 3 жыл бұрын
See the chernos vide9
@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 )
@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.
@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.
@tomaszstanislawski457
@tomaszstanislawski457 2 жыл бұрын
what kind of problems have you encoutered?
@WilliamRaezer
@WilliamRaezer 3 ай бұрын
Why are smartpointers not possible in strict C?
@TheCocoaDaddy
@TheCocoaDaddy 3 жыл бұрын
Great video! Love the t-shirt. :) Thanks for posting!
@JacobSorber
@JacobSorber 3 жыл бұрын
Thanks!
@mintesnotteshale7705
@mintesnotteshale7705 Жыл бұрын
why we cann't assign array for an other array directly?
@christophervaldez2986
@christophervaldez2986 3 жыл бұрын
What IDE/environment is this?
@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?
@SoulSukkur
@SoulSukkur 3 жыл бұрын
C++? what is this malarkey?
@JacobSorber
@JacobSorber 3 жыл бұрын
😀
@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.
@oj0024
@oj0024 3 жыл бұрын
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 жыл бұрын
@@JacobSorber You can check for VLA's using __STDC_NO_VLA__.
@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.
@KamiKagutsuchi
@KamiKagutsuchi 3 жыл бұрын
you should have mentioned std::array when talking about C++
@maxaafbackname5562
@maxaafbackname5562 2 жыл бұрын
And that it is possible to use the sizeof() operator on a fixed size size array parameter when it is passed by reference.
@АрманБектас-б6д
@АрманБектас-б6д Жыл бұрын
Супер
@arielspalter7425
@arielspalter7425 3 жыл бұрын
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#(-:
@NiX_ARG
@NiX_ARG 3 жыл бұрын
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 2 жыл бұрын
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.
@Joao-oo8yj
@Joao-oo8yj Ай бұрын
A think a better approach is to create a struct along with functions that operates on this struct. These functions will abstract and simplify the common process such as resizing.
@anindyamitra5091
@anindyamitra5091 3 жыл бұрын
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.
@shawnmelody8346
@shawnmelody8346 2 жыл бұрын
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.
@astralchan
@astralchan 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?
@sahilshah6635
@sahilshah6635 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 жыл бұрын
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 жыл бұрын
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.
@ng3773
@ng3773 3 жыл бұрын
Hi Jacob, are you planning to do some C++ tutorials?
@d3stinYwOw
@d3stinYwOw 3 жыл бұрын
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 жыл бұрын
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.
@fordfactor
@fordfactor 3 жыл бұрын
Which C standard introduced the ability to size an array with a variable?
@neillunavat
@neillunavat 3 жыл бұрын
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 жыл бұрын
@@not.harshit yep. Thx for reply but sry i figured it out 😁 still, know that this helped me a lot.
@sumdim6427
@sumdim6427 3 жыл бұрын
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...
@sukivirus
@sukivirus 3 жыл бұрын
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 :)
@DemoboyOot
@DemoboyOot 3 ай бұрын
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.
@LingvoScienceUSA
@LingvoScienceUSA 10 ай бұрын
7:00 this is not gonna work, for VLA limitation reasons. It needs to be changed to *#define** ARRAY_LENGTH 5*
@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.
@khankashani7387
@khankashani7387 3 жыл бұрын
Hi dear professor, do you have any C++ 20 tutorials????? Can make C++ tutorials PlesssssssssssssssssssZZZZZZZZZZ!!!!
@VenkatSR-d6m
@VenkatSR-d6m 7 ай бұрын
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 ?
@soniablanche5672
@soniablanche5672 8 ай бұрын
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).
@elalemanpaisa
@elalemanpaisa 12 күн бұрын
no one who is here wants to hear anything about c++ :D thanks for asking Professor
@3dnacho
@3dnacho 3 жыл бұрын
Thanks for the good content. I wold love a video about these tricks to store diferent types in a array in C.
@LingvoScienceUSA
@LingvoScienceUSA 10 ай бұрын
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.
@BinGanzLieb
@BinGanzLieb Жыл бұрын
when you use realloc, the old 15 integers are deleted and the system allocate 20 new integers somewhere in the memory space
@michaelkotthaus7120
@michaelkotthaus7120 3 жыл бұрын
At 11:26, you can also use the function calloc for zero-initialized dynamic memory.
@MrZauberwuerfel
@MrZauberwuerfel 2 жыл бұрын
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 Жыл бұрын
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
@aymankurdi6807
@aymankurdi6807 3 жыл бұрын
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.
@chair547
@chair547 2 жыл бұрын
Arrays? No thanks. I prefer a raise (I don't get paid enough
@pavolkucerak6011
@pavolkucerak6011 Жыл бұрын
Jacob, thank You for this and for other videos.
@aabdev
@aabdev 3 жыл бұрын
What is differential between C11 and C99?
@belesiu
@belesiu 3 жыл бұрын
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.
@R4ngeR4pidz
@R4ngeR4pidz 3 жыл бұрын
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
@tanyasinghal3981
@tanyasinghal3981 3 жыл бұрын
please make a video on vectors
@diegoporras7769
@diegoporras7769 2 жыл бұрын
Great content! Thanks
@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
@ctobi707
@ctobi707 3 жыл бұрын
so a variable length array is a dynamic array under the hood?
@axlslak
@axlslak 3 жыл бұрын
hahaha.... i love you t-shirt teach :)
@JacobSorber
@JacobSorber 3 жыл бұрын
Thanks! 😃
@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?
@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.
@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
@hirokjyotinath2246
@hirokjyotinath2246 3 жыл бұрын
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
@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.
@wassimboussebha2561
@wassimboussebha2561 3 жыл бұрын
can you please talk about 2d arrays ? from a C programmer prospective ( including pointers , addresses .. )
@belesiu
@belesiu 3 жыл бұрын
Is c++ relevant for embedded system programming on small controllers? If so, then yes, let’s learn vectors and containers!
@csbnikhil
@csbnikhil 3 жыл бұрын
Wouldn't myarray[5] in the function parameter be cast to just be a pointer to an int?
@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
@senorpesadillas
@senorpesadillas 3 жыл бұрын
Thank you for this!
@ocrap7
@ocrap7 3 жыл бұрын
This guy deserves A RAISE!
@moeaj1536
@moeaj1536 3 жыл бұрын
We want more c++ videos ❤️
@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.
@BrunoSilva-rr6cb
@BrunoSilva-rr6cb 3 жыл бұрын
What happens when you reallocate to a smaller size?
@JacobSorber
@JacobSorber 3 жыл бұрын
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.
@paulwilliams7647
@paulwilliams7647 2 жыл бұрын
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?
@anshul493
@anshul493 3 жыл бұрын
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..
How to Implement a Tree in C
14:39
Jacob Sorber
Рет қаралды 95 М.
When do I use a union in C or C++, instead of a struct?
11:18
Jacob Sorber
Рет қаралды 69 М.
Inside Out 2: ENVY & DISGUST STOLE JOY's DRINKS!!
00:32
AnythingAlexia
Рет қаралды 10 МЛН
iPhone or Chocolate??
00:16
Hungry FAM
Рет қаралды 39 МЛН
Spongebob ate Michael Jackson 😱 #meme #spongebob #gmod
00:14
Mr. LoLo
Рет қаралды 9 МЛН
Master Pointers in C:  10X Your C Coding!
14:12
Dave's Garage
Рет қаралды 310 М.
Making variables atomic in C
11:12
Jacob Sorber
Рет қаралды 37 М.
Can I Handle Exceptions with Try Catch in C? (setjmp, longjmp)
11:13
why do void* pointers even exist?
8:17
Low Level
Рет қаралды 366 М.
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 787 М.
WHY IS THE STACK SO FAST?
13:46
Core Dumped
Рет қаралды 156 М.
you will never ask about pointers again after watching this video
8:03
Pulling Back the Curtain on the Heap
21:38
Jacob Sorber
Рет қаралды 37 М.
Every Programming Language Ever Explained in 15 Minutes
15:29
Flash Bytes
Рет қаралды 330 М.
Inside Out 2: ENVY & DISGUST STOLE JOY's DRINKS!!
00:32
AnythingAlexia
Рет қаралды 10 МЛН