Dynamically Allocate An Array Of Structs | C Programming Tutorial

  Рет қаралды 33,924

Portfolio Courses

Portfolio Courses

Жыл бұрын

How to dynamically allocate an array of structs in C, including how to use realloc() to re-allocate and increase the size of the array, and a warning about potential memory leaks that can occur if we forget to free dynamically allocated memory that the array struct members themselves point to (including how to prevent the memory leak). Source code: github.com/portfoliocourses/c.... Check out www.portfoliocourses.com to build a portfolio that will impress employers!

Пікірлер: 46
@r0drigo360
@r0drigo360 Жыл бұрын
I was trying to fix a bug for the last 3 hours. I tried StackOverflow and all kinds of forums and couldn't find an answer until I watched your video🙌 Thanks a lot !!!!!!!!!!!
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You're very welcome! :-) I'm glad to hear the video was able to help you out!
@MrSnitsarenko
@MrSnitsarenko 10 ай бұрын
Amazing explanation! I have spent literally a week debugging a code, with googling and many articles StackOverflow etc. Usually big vague paragraphs, and no answer at the end! and here, the author right away clearly points out that you have to allocate memory for struct members as well and use strcpy. Thank you!
@DataToTheZero
@DataToTheZero 4 ай бұрын
Outstanding presentation as always! I'd like to suggest an enhancement to further streamline the management of dynamic memory, especially considering the complexities introduced by structures containing pointers to such memory. Adopting a systematic approach, akin to what one might find in object-oriented languages, by implementing functions that act as creators, modifiers, and destructors for your data structures, can be quite beneficial. Creation: A function to dynamically allocate an array of points. Modification: A function to adjust the size of this array, ensuring efficient memory use. Destruction: A function to properly free the allocated memory, preventing leaks. These concepts encapsulate the complexities of direct memory management, making your code more organized and easier to maintain. This approach is particularly helpful for those transitioning from higher-level, feature-rich languages to C, offering a familiar paradigm to new C programmers. Moreover, it's beneficial to constantly ask yourself, "How would this be handled in a more advanced language?" and then aim to manually implement your version of that solution in C, or find a library that can help. This mindset not only encourages the development of robust, maintainable, and efficient code but also deepens your understanding of what these more advanced languages are doing for you in the background. Understanding these underlying mechanisms can make you a more knowledgeable and versatile programmer, as it provides you with insights into both the high-level abstractions and the low-level implementations that make modern computing possible.
@brendanreeves9645
@brendanreeves9645 Жыл бұрын
Your videos are such lifesavers -- thank you!
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You're welcome Brendan! :-)
@naboulsikhalid7763
@naboulsikhalid7763 5 ай бұрын
one time explained, onetime understood. Thank you a lot
@raptoress6131
@raptoress6131 10 ай бұрын
This is great, I found exactly what I was looking for
@thomasmarczi7345
@thomasmarczi7345 Жыл бұрын
Great video! Thank you so much, it helped a lot! Was having a hard time figuring out what needs to be used to assign my string value to char* property in struct. For some reason array[2].description = "string" overwrote the description property for array[0] and array[1] as well, with the same value. Stackoverflow and other forums didn't help, you did.. it's the strcpy that is needed here!
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You're welcome Thomas, I'm really glad to hear this video helped! :-) And yes, strcpy() is the right approach for sure in this case.
@_karf_
@_karf_ Жыл бұрын
Your video is the answer to all my questions, thank you
@PortfolioCourses
@PortfolioCourses Жыл бұрын
I'm so glad to hear the video answered all your questions, and you're very welcome! :-)
@juanmacias5922
@juanmacias5922 Жыл бұрын
Such a good video, soooooooo much info!
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Thank you for the kind feedback Juan! :-)
@fifaham
@fifaham Жыл бұрын
Thank you Kevin, that was helpful.
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You’re welcome Firas, I’m glad it was helpful! :-)
@thanhcong1349
@thanhcong1349 Жыл бұрын
Thanks for your helpful tutorial video.
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You're welcome Thành, I'm glad it was helpful! :-)
@towtruckn
@towtruckn Жыл бұрын
Kevin; these are great videos. Just a question about freeing memory; is it possible to declare the size of the memory for the description variable inside the struct definition. In this way the free() function would only have to be called once when freeing the memory for any Point variable.
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Yes, you can do that. We could just have: char description[100]; and then the member would just be a regular char array. :-) The only disadvantage to this approach is that even if the description string is much less than the size of description, description would still take up the same fixed amount of space (in this case 100 bytes). But in many circumstances this doesn't really matter and it would be fine to use a fixed size.
@dimitrioskalfakis
@dimitrioskalfakis Жыл бұрын
very nice. simple and useful.
@PortfolioCourses
@PortfolioCourses Жыл бұрын
I'm glad you found and simple and useful Dimitrios! :-)
@norbertracz1009
@norbertracz1009 Жыл бұрын
Thaks!
@yue7507
@yue7507 Жыл бұрын
Thank you!
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You're welcome! :-)
@ramakrishna4092
@ramakrishna4092 Жыл бұрын
Hi sir one question here we can use -> operator there also like (array+2)->y=3; can you pls reply to me whether it's right or wrong....
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Yes, that will work too. :-)
@HoangNguyen-nz4xe
@HoangNguyen-nz4xe 6 ай бұрын
Hi, i have a question: while allocating memory, i saw lots of people doing this (int*)malloc(...) is it necessary or just nice to have. Does it cause any issues? Thank you.
@Hackathons-wf1lg
@Hackathons-wf1lg Жыл бұрын
where did you learn how to program in C so well? Also thoughts on CPP?
@PortfolioCourses
@PortfolioCourses Жыл бұрын
I've worked with C a fair bit over the years and taught it as well, it's always been one of my favourite languages because it is so simple compared to most others. CPP is great to know if you want to work in certain industries, like AAA games for example. As a language, I do like it, but there are so many different ways of doing so many different things that are all technically "valid" that the language can be frustrating too. In industry lots of people will actually use a subset of C++, so they'll use a particular style or limit themselves to a subset of C++. For OO languages, I prefer Python. :-)
@mikehibbett3301
@mikehibbett3301 5 ай бұрын
I've been designing embedded systems for 35 years now, and I've never had to use dynamic memory, or floating point datatypes. I'm curious if anyone else had the same experience? I've been on a few architecture design reviews where I've had some pushback, but we ended up without needing malloc.
@moncho3115
@moncho3115 Жыл бұрын
esta genial el video
@PortfolioCourses
@PortfolioCourses Жыл бұрын
gracias! :-)
@goktugparlak1618
@goktugparlak1618 Жыл бұрын
What happens if they wrote like this Point *array[100] is it means without malloc is it allocates space by itself what is it means. My prof wrotes like that
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Then you would have an array of 100 pointers to Point structs. :-) That's a good way of working with structs too!
@marlburo6889
@marlburo6889 8 ай бұрын
Insane
@Jarvx
@Jarvx Жыл бұрын
Hey there, what IDE is that?
@PortfolioCourses
@PortfolioCourses Жыл бұрын
This is Xcode on a Mac. :-)
@grimvian
@grimvian Жыл бұрын
Well done, you deserve to grow in subscripsions and I'm learning a lot. I'm actually not using an array when dealing with allocated structs yet. It may be a wrong approch, but I find it easier to use an extra pointer to manipulate the allocated memory and move the size of the struct. What do you think? int num = 2; point *mem = malloc(sizeof(point) * num); point *p1 = mem; p1->x = 3; p1->y = 2; p1++; p1->x = 6; p1->y = 1; p1--; int i = 0; while (i++ < num) { printf("%d, %d ", p1->x, p1->y); p1++; } free(mem);
@PortfolioCourses
@PortfolioCourses Жыл бұрын
You’re welcome!! :-) And this looks OK to me, just out of curiosity, why do you like to use an extra pointer? Is it so you can always just free the original pointer variable when you’re done with it?
@grimvian
@grimvian Жыл бұрын
@@PortfolioCourses Exactly :-) An idea I came up with after some crashes, until I understood what was going on using the GDB debugger. I was of cource trying to free the wrong memory address. If understand your question correctly, it's indicating it's not the normal or maybe even the wrong way to use allocations?
@vinmo8326
@vinmo8326 Жыл бұрын
👍👍👍
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Thank you! :-)
@michaeljames7232
@michaeljames7232 Жыл бұрын
Thank you for your Vide. I am having trouble with malloc when I put the following linse: Point *p2; p2 = malloc(sizeof(Point)); I get the error : Severity Code Description Project File Line Suppression State Error (active) E0513 a value of type "void *" cannot be assigned to an entity of type "Point *" StructSub C:\Users\mvj32\source epos\StructSub\StructSub\Source.cpp 21 lude #include typedef struct { int x; int y; } Point; int main() { Point p1; p1.x = 4; p1.y = 5; printf("(%d, %d) ", p1.x, p1.y); Point *p2; p2 = malloc(sizeof(Point)); return 0; }
@PortfolioCourses
@PortfolioCourses Жыл бұрын
Great question Michael! :-) I notice the file is ".cpp", which is for C++. When using C++, or even a C++ compiler to compile what is otherwise a C program, it is mandatory to typecast the return value of malloc. In C it is not mandatory. So this is very likely why it is failing. Putting (Point *) in front of that call to malloc might fix the issue. Good luck!
@user-pd1sx9tx4q
@user-pd1sx9tx4q 10 ай бұрын
Amazing explanation! I have spent literally a week debugging a code, with googling and many articles StackOverflow etc. Usually big vague paragraphs, and no answer at the end! and here, the author right away clearly points out that you have to allocate memory for struct members as well and use strcpy. Thank you!
How To Return A String From A Function | C Programming Tutorial
13:51
Portfolio Courses
Рет қаралды 15 М.
Dynamically Allocate A 2D Array | C Programming Tutorial
15:58
Portfolio Courses
Рет қаралды 34 М.
Survive 100 Days In Nuclear Bunker, Win $500,000
32:21
MrBeast
Рет қаралды 76 МЛН
What it feels like cleaning up after a toddler.
00:40
Daniel LaBelle
Рет қаралды 89 МЛН
Slow motion boy #shorts by Tsuriki Show
00:14
Tsuriki Show
Рет қаралды 10 МЛН
Structs in C | What you Need to Know
24:39
Caleb Curry
Рет қаралды 9 М.
Dynamic Arrays in C
11:46
Dylan Falconer
Рет қаралды 65 М.
why do void* pointers even exist?
8:17
Low Level Learning
Рет қаралды 344 М.
Dynamic Memory Allocation | C Programming Tutorial
31:51
Portfolio Courses
Рет қаралды 80 М.
Read CSV File Data Into An Array Of Structs | C Programming Example
11:05
Portfolio Courses
Рет қаралды 41 М.
Dynamically Allocate Memory For An Array Of Strings | C Programming Example
12:10
How To Return An Array From A Function | C Programming Tutorial
13:01
Portfolio Courses
Рет қаралды 64 М.
String In Char Array VS. Pointer To String Literal | C Programming Tutorial
9:58
you will never ask about pointers again after watching this video
8:03
Low Level Learning
Рет қаралды 2,1 МЛН
Dynamic Memory with Malloc - Everything you Need to Know
13:51
Caleb Curry
Рет қаралды 8 М.
Survive 100 Days In Nuclear Bunker, Win $500,000
32:21
MrBeast
Рет қаралды 76 МЛН