Dynamically Allocate Memory For An Array Of Strings | C Programming Example

Поделиться
HTML-код
  • Опубликовано: 24 янв 2025

Комментарии • 103

  • @PortfolioCourses
    @PortfolioCourses  2 года назад +35

    HOW TO FREE THE MEMORY:
    /* free each string pointer in a loop */
    for (int i = 0; i < total; i++)
    free(strings[i]);
    /* free pointer to strings */
    free(strings);

    • @zoquevil4792
      @zoquevil4792 2 года назад

      Super intersting even though I didn't see the buffer (for a file) yet !!! I was just interested to the point of using the funciont free() after creating an array of pointer vs array of string!!! I forgot that we need to free every string pointer of the array (not easy to talk about an array of string whent we are talking at the same time about pointer )
      thanks for this example!!!

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      @@zoquevil4792 You're welcome! 😀

    • @philipphortnagl2486
      @philipphortnagl2486 2 года назад

      just to be sure: you free the space after you used it, right? so this line of code comes at the very end after you printed out the arrays and don't plan to use it again?! And also, isn't it enough to just use free(strings) alone? Why is the for loop with free(strings[i]) necessary? I thought free(strings) will free the pointer..?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +2

      @@philipphortnagl2486 Yes, you would free the memory after you're done using the memory. And the reason we need to free strings[i] in the loop is that each of those is its own 1D char array that was allocated with separate calls to malloc(). When we free(strings) we are free-ing the 1D array of pointers to these 1D char arrays, but we need to call free(strings[i]) for *each* of these 1D char arrays as well to free all the space. 🙂

  • @mensaswede4028
    @mensaswede4028 11 месяцев назад +9

    These are great C tutorials. I’ve probably written over a million lines of C code over the last 35 years, and this series hits all the important points a beginner needs to learn to become proficient in C.

  • @withthehelp6291
    @withthehelp6291 3 года назад +8

    This is exactly what I need for my Cs exam

  • @arasunatesan1970
    @arasunatesan1970 10 месяцев назад +1

    You are very impressive
    God bless you
    I teach basics of c, free to rural students
    Your videos are quite helpful
    🙏

  • @fifaham
    @fifaham Год назад

    The most important is at time frame @11:34 from Canada LOL - nice video. Thank you Kevin.

  • @patchavavengalraovengalrao3784
    @patchavavengalraovengalrao3784 2 года назад +2

    after watching few videos of this channel. i got some super powers

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      That’s awesome Patchava! Learning to code totally feels like gaining a super power. :-)

  • @Rai_Te
    @Rai_Te Год назад +1

    Error at 0:58 , where you 'malloc (sizeof(char) * length)' for a string of length bytes.
    You either forgot to mention, that the length MUST include the trailing '\0' or you should
    'malloc (sizeof(char) * (length+1))' in order to add the required one byte for the trailing zero-byte.
    Forgetting to allocate the additional byte for the trailing zero is a common mistake among beginners,
    and it leads to a certain amount of frustration as these errors usually do not show up immediately.
    That's why it cannot be emphasised enough.

  • @prumchhangsreng979
    @prumchhangsreng979 2 года назад +2

    For the love of god i couldnt figure out how to do this. Thanks god u made a video for this. Just TAKE MY THANKS LIKE SUB

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      I’m very glad to hear it helped you out Prum! And thank you for the like sub! :-)

  • @technicalgamer2565
    @technicalgamer2565 2 года назад

    Man i was so confused by this topic you just rocked thx

  • @sergioberezovski4865
    @sergioberezovski4865 2 года назад

    thanks for helping me finish my project for this semester ✅

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      You're welcome Sergio, I'm glad you found these videos helpful, and good luck on your project! :-)

  • @rotemlv
    @rotemlv 2 года назад +4

    I prefer the "direct" allocation syntax, as it seems to be less error prone. I mean, by using the dereferenced pointer as an operand with the sizeof keyword:
    p = malloc(how_many * sizeof * p);
    Let's say the char is now wchar_t or something, no need to worry about missing all these.
    Will not work with cpp as far as I remember though.

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Cool! :-) Thank you for sharing this approach Rotem.

  • @ninadgandhi9040
    @ninadgandhi9040 2 года назад +1

    Amazing, cleared all my doubts and even taught me new stuff! Thank you so much

  • @eighteen7875
    @eighteen7875 3 года назад

    nice bro! its very kind that ur helping ur subs

    • @PortfolioCourses
      @PortfolioCourses  3 года назад +1

      Thank you! I figure if someone is asking a question that means 1000 other people have that question too. I have a big list of like 20 videos now to work on though haha…

  • @MARCBOSCHMANZANO
    @MARCBOSCHMANZANO Год назад +1

    You solve my problem! Lots of thanks🧡🧡

    • @PortfolioCourses
      @PortfolioCourses  Год назад

      You’re welcome Marc, I’m glad the video solved your problem! :-)

  • @bettyswunghole3310
    @bettyswunghole3310 6 месяцев назад

    A very useful video! Thank you!

  • @educationandmore
    @educationandmore 2 года назад

    Excellent job. You should also show similar version where reading from a file.

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      That's definitely a topic I want to do one day Markis! 🙂 For now I have this video: ruclips.net/video/X-1qodkHCHo/видео.html. The array is not dynamic though, that's what I will make a future video on when I'm able to.

  • @justcurious1940
    @justcurious1940 Год назад

    Nice video, Thanks.

  • @technicalgamer2565
    @technicalgamer2565 2 года назад +1

    one question : when we say char * name = "something"; why we dont need to malloc bcs name is just pointer. Is the "something " is in heap or stack pls tell

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      So that’s a great question! :-) I actually made a video that addresses this topic and what is happening here: String In Char Array VS. Pointer To String Literal | C Programming Tutorial
      ruclips.net/video/Qp3WatLL_Hc/видео.html

    • @technicalgamer2565
      @technicalgamer2565 2 года назад

      Thx man

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      You’re welcome! :-)

  • @veggieboy1
    @veggieboy1 2 года назад +1

    THANK YOU!!!! I had not realised it was this simple! I had always been confused by the fact that the double pointer is simply an array of pointers and does not contain the strings themselves! Just one question, could you use realloc() on the double **ptr to dynamically resize the array of strings (say, if you don't know from the start the number of strings that will be stored)?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      You're welcome! And yes, you could use realloc like that to dynamically re-size the array of strings.

    • @veggieboy1
      @veggieboy1 2 года назад

      @@PortfolioCourses Cheers!

  • @ahmadalwazzan363
    @ahmadalwazzan363 2 года назад

    Thanks you
    Could you demonstrate an example of reading files into a dynamic memory and printing them. Couldn't find anything useful

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      You're welcome Ahmad... that's definitely on my list of video ideas. 🙂

  • @aliali-gg7xu
    @aliali-gg7xu 2 года назад

    great video!!thank you! i still have a question.. so if strings[i] points to the i'th string then how should i go to access a specific word from the string ? something like strings[i][j] ?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Accessing the different words in a string is a bit of a hard problem. Using a second index is something we would do to access a particular index in a string. But if we want to access a word in a string, we need to know index of that word in order for that to work. So yes, if you know the word is at index j, then yes that's how you could do it. :-) But if you don't know where the word is you would need to write some other code to find the word you're looking for.

  • @philipphortnagl2486
    @philipphortnagl2486 2 года назад

    Great! a question though: would this work also without a buffer variable? Why I cannot directly store into my strings?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Great question Philipp! :-) And yes you could do it without a buffer variable if you know the size of the strings in advance, or you are willing to use realloc() to modify the size of the space allocated to store a string if you find out that you need more space (or perhaps less space).

    • @philipphortnagl2486
      @philipphortnagl2486 2 года назад

      @@PortfolioCourses Ah alright, but knowing the strings in advance would be a totally different concept. Ok I understand now more the concept of pointers and dyn mem alloc! thanks

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      @@philipphortnagl2486 You're welcome! 🙂

  • @KaizoKitsune625
    @KaizoKitsune625 Год назад

    I have another question is it necessary to use getch and fgets because what if you were going to input the strings instead

    • @PortfolioCourses
      @PortfolioCourses  Год назад

      No it is not necessary to use getch or fgets, you can input the strings however you like. :-)

  • @brycenava414
    @brycenava414 2 года назад

    thanks for this tutorial! Can you also make a video on how to cut strings before a symbol/character, then returning it to main, printing it on the terminal and saving the new string to a file? I’ve been racking my brain on how to cut an email address string before the @, then return and save it on a file, but i keep getting weird symbols with it

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Hi Bryce, maybe one day I can make a video like that. 🙂 In the meantime, this video might help you with the string splitting part: ruclips.net/video/Vp6OELK4gmo/видео.html. The rest of it may be covered by other videos like this one on File I/O Basics: ruclips.net/video/HQNsriyMhtY/видео.html.

  • @pnuema1.618
    @pnuema1.618 2 года назад

    One question. Why bother weighing the code down with multiplication in malloc when you are multiplying by 1?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Do you mean multiplying by sizeof(char)? That's there for portability, in-case the size of a char changes or is different on one system than another, it should still work. The sizeof(char) function also gets evaluated at compile time, and not run time. So the compiler will replace sizeof(char) with the size of a character when the code is compiled, it won't be calling a sizeof() function every time. When sizeof(char) evaluates to 1, and we have a multiplication by 1 occurring, the compiler will end up just removing it entirely. But we still keep it there for portability reasons, and I suppose readability reasons. Personally, I wouldn't consider it wrong to take it out either if you don't care about portability.

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Interestingly, I was researching for another video today and learned that sizeof(char) should always be 1 byte no matter the system (though what is considered a bye could change). stackoverflow.com/a/2215454. It seems like people still use sizeof(char) for 'uniformity', whether that's worth it or not I don't know, either way I'm sure the compiler will optimize it out:
      www.quora.com/In-C-is-it-a-good-practice-to-use-code-C-sizeof-char-code-instead-of-code-C-1-code
      cs50.stackexchange.com/questions/28717/why-we-use-sizeofchar

  • @sudhadevi6692
    @sudhadevi6692 2 года назад

    Hey brother ..
    I have a problem.
    I have to take input from user the length of character he want to give. And make a dynamic array of characters using malloc on based of GIVEN LENGTH.
    Then I am taking input from user in gets() And printing by puts().
    #include
    #include
    #include
    Void main()
    {
    int size;
    char *name;
    printf("enter size");
    scanf("%d",size);
    name=(char *)malloc(sizeof(char)*size);
    printf("enter name");
    gets(name);
    puts(name);
    }
    After taking size the code terminates why. But the same code is running with scanf on behalf of gets .
    Plz help.😣

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Great question Sudha! :-) I believe the issue is that after using scanf() to read in the int, a a newline is left in "standard input" from the user hitting enter. As a result, the call to gets() sees the newline in standard input and stores a blank string. Before using gets() you should clear the standard input buffer, this might help: www.geeksforgeeks.org/use-fflushstdin-c/. Also, I do not recommend using gets(): ruclips.net/video/WXnWoRJ7WyU/видео.html.

  • @mefrefgiweuhef4808
    @mefrefgiweuhef4808 2 года назад

    dude THANK U!!

  • @alicem7954
    @alicem7954 2 года назад

    Thanks! Can I ask what if we don’t know the total numbers of strings ?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Great question Alice! :-) In that case, we would likely need to use realloc(): ruclips.net/video/vr7qCQLrUt8/видео.html . realloc() allows us to make a block of allocated memory larger or smaller as needed. So we could use realloc() to make the array of pointers to chars larger as needed, if we discover later that we need to store more strings.

  • @qneqne8440
    @qneqne8440 Год назад

    When you use printf in your tutorials, I see that you use %d where you can instead use %i (I feel the d means double and i means integar correct me if I'm wrong) My question is why use %d and not %i what's the difference/harm?

    • @PortfolioCourses
      @PortfolioCourses  Год назад

      There isn't much difference, you can use %i if you prefer, but %d is more widely used. This article goes over the differences, where %i detects the base but %d does not when using scanf: www.geeksforgeeks.org/difference-d-format-specifier-c-language/. :-)

  • @dhakad22klx
    @dhakad22klx Год назад

    Helpful😍

  • @marcboschmanzano1642
    @marcboschmanzano1642 Год назад

    Hello! What IDE do you use?

    • @PortfolioCourses
      @PortfolioCourses  Год назад

      Hi Marc! :-) In this video I am using Xcode on an Apple computer.

  • @4rumani
    @4rumani 2 месяца назад

    Thanks

  • @thesinceremaverick
    @thesinceremaverick Год назад

    Sir, please also make a video on 2d array of strings.

    • @PortfolioCourses
      @PortfolioCourses  Год назад +1

      Ok I will add that to my list of video ideas! :-)

    • @ziwaang2250
      @ziwaang2250 Год назад

      @@PortfolioCourses This would be really helpful! Thank you for all the work you do!

  • @sukshithshetty4847
    @sukshithshetty4847 2 года назад

    Can i use fflush(stdin) instead of while (getchar() != '
    ');??

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Great question Sukshith. :-) So technically in C fflush is not guaranteed to work with the stdin stream, but as a practical matter I’m not aware of any C compilers that do not allow it. So as a practical matter it will work, but technically it could make your code less portable to other compilers because it’s not “officially” part of the C standard.

  • @manethdulshan9449
    @manethdulshan9449 7 месяцев назад

    Thank youuu

  • @KaizoKitsune625
    @KaizoKitsune625 Год назад

    for char **strings why is a double pointer used?

    • @PortfolioCourses
      @PortfolioCourses  Год назад

      That's a great question. :-) Each string is a sequence characters. And char * will store a pointer (i.e. a memory address) of the first character in the string. But char **strings is not a pointer to a char. It's a pointer to an array of pointers to chars... i.e. a pointer to the array of pointers to our strings. So that's why we have a double pointer... we have a pointer to a pointer. strings will point (i.e. store the memory address of) the first char * in the array of char *'s to each string. This video might help to explain things better too: ruclips.net/video/ZLc_OpzND2c/видео.html. :-)

  • @technicalgamer2565
    @technicalgamer2565 2 года назад

    respect from india pls clear my doubt

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      I hope the video that I shared is able to help you, thanks again from Canada! :-)

  • @warplanner8852
    @warplanner8852 2 года назад

    Somehow, my previous comment re memory leaks got cached away. Allow a more detailed comment and a question about how to eliminate memory leaks in this particular case:
    (1) I am using MSVC++ Visual Studio 2008 and the source of your app has been imbued with the debug malloc() and free() calls, etc. The code in your very fine example contains NO free(0 calls for the dynamically allocated memory and, hence, incurs memory leaks: one of the original _char** strings_ variable malloc() and one fore each string that the user inputs -- because each incurs a malloc() call.
    (2) In order to free() the allocated heap memory, I placed a free statement in the printf() loop:
    for (i = 0; i < total; i++)
    {
    ....printf("strings [%d] = [%s]
    ", i, strings[i]);
    ....free(strings[i]);

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Yes the code does not free the memory, that is something that could be done when it's no longer needed. I am thinking of making a video on this specifically now, or uploading a new version of this video. 🙂 To free the memory, including the original strings** memory allocation, you could do this at the end of the program after the original version of the print loop:
      /* free each string pointer in a loop */
      for (int i = 0; i < total; i++)
      free(strings[i]);
      /* free pointer to strings */
      free(strings);
      I'm not sure how well that would play with the crtdbg.h library and MSVC++ Visual Studio 2008, but I think it should work.

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Was this comment cut short? Or is Bu slang that I don’t understand maybe? :-)

    • @warplanner8852
      @warplanner8852 2 года назад

      @@PortfolioCourses The first comment was cached and I could not follow up. But, before I go further, I should like to compliment you on your effort. Your lessons are very well constructed and your style of instruction is patient and very clear.
      I have been developing software for over 45 years (mostly IBM mainframe for the first 10 years and then C/C++/Assembler for the remainder.) I found my career was so much of a rush to meet deadlines that the elegance of the languages (mostly C) was lost on me and wanted go back to basics now that I am retired. Back to the question at hand:
      I was not successful in answering my own question but will stumble upon it one day. It appears that the "n" added strings can be freed buy iterating through them with for() loop. But the original allocation of the _char** strings_ variables heap memory plays havoc with the _MSVC CRTDBG_ code found in the _crtdbg.h_ header.
      The original malloc() of strings occupies the same address as strings[0] (of course) and attempting to free it (twice) is a no no. If you free the strings[n] heap memory, the CRTDBG _reports_ a leak -- but of zero bytes.
      Similarly, freeing the _strings_ memory reports leaks for strings[1], strings[2] through strings[n] with orphaned heap memory. So, I am forced to conclude conclude that the way to go is to walk through a free() from 0 to n until find out what the magic incantation is.
      I will try this with gcc and find out what's what!
      Finally, your video on free() is more that adequate to cover this subject. (It's quite good, in fact.) Let your new guys bust their knuckles; it's how one learns.
      All the best and keep up the good work!
      _William_

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      Thanks for the kind words and the detailed comment William! That’s a really cool career you’ve had, I bet people would like to hear about your experience. And I’m going to check out what you’re saying here regarding freeing the dynamically allocated memory, maybe it’s something I can do a video on or something for fun. :-)

    • @warplanner8852
      @warplanner8852 2 года назад

      @@PortfolioCourses NP. I am casting about for the equivalent cross-platform _crtdbg_ memory leak tracers and will get back to you if I can find anything.

  • @joeunderwood8973
    @joeunderwood8973 8 месяцев назад

    5:02 `while(getchar() != '
    ');` WHOA if `getchar() == EOF` you have an infinite loop!

  • @ryanalnaser914
    @ryanalnaser914 2 года назад +1

    whatever anything I do or did or after or anything and thanks and anything I do or did

    • @ryanalnaser914
      @ryanalnaser914 2 года назад

      whatever anything I do or did or anything or know or did not know

  • @TheAcebyte
    @TheAcebyte 5 месяцев назад

    Thank you for the video! The one question I have is, would it not be necessary to typecast the malloc?

    • @PortfolioCourses
      @PortfolioCourses  5 месяцев назад

      No, it's necessary in C++ but not C: ruclips.net/video/KTbY4-chkcs/видео.html

    • @TheAcebyte
      @TheAcebyte 5 месяцев назад

      @@PortfolioCourses Wow, that was a quick response, thank you so much!

  • @zarifhossain8817
    @zarifhossain8817 2 года назад

    don’t we need to free the space?

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      Yes, we should also use free to free all of the dynamically allocated memory. In a program this short once it terminates the memory is freed, but in a 'real program' it's very important we free the memory too.

    • @Brock-Landers
      @Brock-Landers 2 года назад +1

      /* free each string pointer in a loop */
      for (int i = 0; i < total; i++)
      free(strings[i]);
      /* free pointer to strings */
      free(strings);

    • @PortfolioCourses
      @PortfolioCourses  2 года назад

      @@Brock-Landers Yes, that's how to free the memory. 🙂

  • @wc3815
    @wc3815 2 года назад

    how to free all the memory? 😭

    • @PortfolioCourses
      @PortfolioCourses  2 года назад +1

      You could do this to free the memory once you are done with it:
      /* free each string pointer in a loop */
      for (int i = 0; i < total; i++)
      free(strings[i]);
      /* free pointer to strings */
      free(strings);

  • @wurbo3488
    @wurbo3488 Год назад

    .

  • @svenbb4937
    @svenbb4937 8 месяцев назад +1

    Let's be honest: Someone who needs to ask how to allocate memory for an array of strings in C, should read (and work through) some programming book like "C Programming: A Modern Approach" or "C Programming Language" instead of watching a youtube video.