Тёмный

Fixed and Variable Length Arrays in C and C++ 

Jacob Sorber
Подписаться 165 тыс.
Просмотров 45 тыс.
50% 1

Опубликовано:

 

26 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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?
@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.
@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.
@brambeer5591
@brambeer5591 3 года назад
Thanks, outstanding video! Especially the comparison with cpp code adds extra educational value.
@JacobSorber
@JacobSorber 3 года назад
Glad it was helpful!
@pavolkucerak6011
@pavolkucerak6011 Год назад
Jacob, thank You for this and for other videos.
@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...
@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.
@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#(-:
@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.
@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.
@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.
@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.
@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 :)
@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.
@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.
@diegoporras7769
@diegoporras7769 2 года назад
Great content! Thanks
@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.
@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
@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.
@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 )
@ng3773
@ng3773 3 года назад
Hi Jacob, are you planning to do some C++ tutorials?
@michaelkotthaus7120
@michaelkotthaus7120 3 года назад
At 11:26, you can also use the function calloc for zero-initialized dynamic memory.
@TheCocoaDaddy
@TheCocoaDaddy 3 года назад
Great video! Love the t-shirt. :) Thanks for posting!
@JacobSorber
@JacobSorber 3 года назад
Thanks!
@senorpesadillas
@senorpesadillas 3 года назад
Thank you for this!
@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
@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
@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 ?
@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.
@moeaj1536
@moeaj1536 3 года назад
We want more c++ videos ❤️
@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?
@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
@fordfactor
@fordfactor 3 года назад
Which C standard introduced the ability to size an array with a variable?
@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.
@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?
@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?
@WilliamRaezer
@WilliamRaezer 3 месяца назад
Why are smartpointers not possible in strict C?
@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.
@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
@tanyasinghal3981
@tanyasinghal3981 3 года назад
please make a video on vectors
@wassimboussebha2561
@wassimboussebha2561 3 года назад
can you please talk about 2d arrays ? from a C programmer prospective ( including pointers , addresses .. )
@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.
@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?
@aabdev
@aabdev 3 года назад
What is differential between C11 and C99?
@csbnikhil
@csbnikhil 3 года назад
Wouldn't myarray[5] in the function parameter be cast to just be a pointer to an int?
@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.
@mintesnotteshale7705
@mintesnotteshale7705 Год назад
why we cann't assign array for an other array directly?
@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..
@SoulSukkur
@SoulSukkur 3 года назад
C++? what is this malarkey?
@JacobSorber
@JacobSorber 3 года назад
😀
@christophervaldez2986
@christophervaldez2986 3 года назад
What IDE/environment is this?
@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
@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
@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.
@elalemanpaisa
@elalemanpaisa 10 дней назад
no one who is here wants to hear anything about c++ :D thanks for asking Professor
@ctobi707
@ctobi707 3 года назад
so a variable length array is a dynamic array under the hood?
@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__.
@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).
@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?
@khankashani7387
@khankashani7387 3 года назад
Hi dear professor, do you have any C++ 20 tutorials????? Can make C++ tutorials PlesssssssssssssssssssZZZZZZZZZZ!!!!
@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.
@belesiu
@belesiu 3 года назад
Is c++ relevant for embedded system programming on small controllers? If so, then yes, let’s learn vectors and containers!
@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.
@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.
@LingvoScienceUSA
@LingvoScienceUSA 10 месяцев назад
7:00 this is not gonna work, for VLA limitation reasons. It needs to be changed to *#define** ARRAY_LENGTH 5*
@АрманБектас-б6д
Супер
@chair547
@chair547 2 года назад
Arrays? No thanks. I prefer a raise (I don't get paid enough
@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.
@BinGanzLieb
@BinGanzLieb Год назад
when you use realloc, the old 15 integers are deleted and the system allocate 20 new integers somewhere in the memory space
@axlslak
@axlslak 3 года назад
hahaha.... i love you t-shirt teach :)
@JacobSorber
@JacobSorber 3 года назад
Thanks! 😃
@ocrap7
@ocrap7 3 года назад
This guy deserves A RAISE!
Далее
How to Implement a Tree in C
14:39
Просмотров 95 тыс.
Pulling Back the Curtain on the Heap
21:38
Просмотров 37 тыс.
Свожу все свои тату (abricoss_a_tyt)
00:35
Master Pointers in C:  10X Your C Coding!
14:12
Просмотров 309 тыс.
31 nooby C++ habits you need to ditch
16:18
Просмотров 786 тыс.
What's the Best Way to Copy a Struct in C and C++?
13:44
C++ Pointers - Finally Understand Pointers
15:56
Просмотров 213 тыс.
The What, How, and Why of Void Pointers in C and C++?
13:12
WHY IS THE STACK SO FAST?
13:46
Просмотров 155 тыс.