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

Sdílet
Vložit
  • čas přidán 20. 01. 2022
  • How to dynamically allocate memory for an array of strings using C. Source code: github.com/portfoliocourses/c.... Check out www.portfoliocourses.com to build a portfolio that will impress employers!
  • Jak na to + styl

Komentáře • 100

  • @PortfolioCourses
    @PortfolioCourses  Před 2 lety +31

    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 Před rokem

      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  Před rokem

      @@zoquevil4792 You're welcome! 😀

    • @philipphortnagl2486
      @philipphortnagl2486 Před rokem

      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  Před rokem +1

      @@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 Před 5 měsíci +4

    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.

  • @technicalgamer2565
    @technicalgamer2565 Před rokem

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

  • @bettyswunghole3310
    @bettyswunghole3310 Před 19 dny

    A very useful video! Thank you!

  • @eighteen7875
    @eighteen7875 Před 2 lety

    nice bro! its very kind that ur helping ur subs

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety +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…

  • @arasunatesan1970
    @arasunatesan1970 Před 4 měsíci

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

  • @MARCBOSCHMANZANO
    @MARCBOSCHMANZANO Před rokem +1

    You solve my problem! Lots of thanks🧡🧡

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

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

  • @ninadgandhi9040
    @ninadgandhi9040 Před 2 lety +1

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

  • @withthehelp6291
    @withthehelp6291 Před 2 lety +7

    This is exactly what I need for my Cs exam

  • @sergioberezovski4865
    @sergioberezovski4865 Před rokem

    thanks for helping me finish my project for this semester ✅

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

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

  • @justcurious1940
    @justcurious1940 Před 7 měsíci

    Nice video, Thanks.

  • @kuijaye
    @kuijaye Před 2 lety +8

    Thanks a lot!
    I was confused by the getchar part (I thought getchar() does not read '
    ' in the course of while loop! :). Then I read some articles on the internet and noticed, getchar() reads all the characters up to and including '
    '. Basically getchar() is called before even it compares the character with line feed. So, at the end, the '
    ' has been read (and therefore flushed), the returned character, '
    ', is compared to '
    ', and we exit the loop.

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety

      You’re welcome Ali! :-) And yes you’ve got it figured out right!

  • @fifaham
    @fifaham Před rokem

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

  • @prumchhangsreng979
    @prumchhangsreng979 Před 2 lety +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  Před 2 lety

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

  • @educationandmore
    @educationandmore Před 2 lety

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

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety

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

  • @rotemlv
    @rotemlv Před rokem +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.

  • @patchavavengalraovengalrao3784

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

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

  • @brycenava414
    @brycenava414 Před 2 lety

    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  Před 2 lety +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: czcams.com/video/Vp6OELK4gmo/video.html. The rest of it may be covered by other videos like this one on File I/O Basics: czcams.com/video/HQNsriyMhtY/video.html.

  • @Rai_Te
    @Rai_Te Před 6 měsíci +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.

  • @Walkingdeadman1991
    @Walkingdeadman1991 Před 2 lety +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  Před 2 lety +1

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

    • @Walkingdeadman1991
      @Walkingdeadman1991 Před 2 lety

      @@PortfolioCourses Cheers!

  • @mefrefgiweuhef4808
    @mefrefgiweuhef4808 Před 2 lety

    dude THANK U!!

  • @aliali-gg7xu
    @aliali-gg7xu Před rokem

    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  Před rokem

      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.

  • @manethdulshan9449
    @manethdulshan9449 Před měsícem

    Thank youuu

  • @ahmadalwazzan363
    @ahmadalwazzan363 Před rokem

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

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

  • @dhakad22klx
    @dhakad22klx Před rokem

    Helpful😍

  • @KaizoKitsune625
    @KaizoKitsune625 Před rokem

    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  Před rokem

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

  • @philipphortnagl2486
    @philipphortnagl2486 Před rokem

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +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 Před rokem

      @@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  Před rokem

      @@philipphortnagl2486 You're welcome! 🙂

  • @sudhadevi6692
    @sudhadevi6692 Před rokem

    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  Před rokem

      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(): czcams.com/video/WXnWoRJ7WyU/video.html.

  • @alicem7954
    @alicem7954 Před rokem

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

      Great question Alice! :-) In that case, we would likely need to use realloc(): czcams.com/video/vr7qCQLrUt8/video.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.

  • @technicalgamer2565
    @technicalgamer2565 Před rokem +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  Před rokem +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
      czcams.com/video/Qp3WatLL_Hc/video.html

    • @technicalgamer2565
      @technicalgamer2565 Před rokem

      Thx man

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

      You’re welcome! :-)

  • @pnuema1.618
    @pnuema1.618 Před 2 lety

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

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety +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  Před 2 lety +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

  • @sukshithshetty4847
    @sukshithshetty4847 Před rokem

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

      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.

  • @marcboschmanzano1642
    @marcboschmanzano1642 Před rokem

    Hello! What IDE do you use?

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

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

  • @qneqne8440
    @qneqne8440 Před rokem

    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  Před rokem

      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/. :-)

  • @technicalgamer2565
    @technicalgamer2565 Před rokem

    respect from india pls clear my doubt

    • @PortfolioCourses
      @PortfolioCourses  Před rokem +1

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

  • @paulpranshu
    @paulpranshu Před 8 měsíci

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

    • @PortfolioCourses
      @PortfolioCourses  Před 8 měsíci +1

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

    • @ziwaang2250
      @ziwaang2250 Před 8 měsíci

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

  • @KaizoKitsune625
    @KaizoKitsune625 Před rokem

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

    • @PortfolioCourses
      @PortfolioCourses  Před rokem

      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: czcams.com/video/ZLc_OpzND2c/video.html. :-)

  • @ryanalnaser914
    @ryanalnaser914 Před 2 lety +1

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

    • @ryanalnaser914
      @ryanalnaser914 Před 2 lety

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

  • @warplanner8852
    @warplanner8852 Před 2 lety

    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  Před 2 lety

      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  Před 2 lety

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

    • @warplanner8852
      @warplanner8852 Před 2 lety

      @@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  Před 2 lety

      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 Před 2 lety

      @@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 Před 2 měsíci

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

  • @wc3815
    @wc3815 Před 2 lety

    how to free all the memory? 😭

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety +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);

  • @zarifhossain8817
    @zarifhossain8817 Před 2 lety

    don’t we need to free the space?

    • @PortfolioCourses
      @PortfolioCourses  Před 2 lety +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 Před 2 lety +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  Před 2 lety

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

  • @svenbb4937
    @svenbb4937 Před 2 měsíci +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.

  • @wurbo3488
    @wurbo3488 Před 8 měsíci

    .