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

Поділитися
Вставка
  • Опубліковано 30 вер 2024
  • How to dynamically allocate memory for an array of strings using C. Source code: github.com/por.... Check out www.portfolioc... to build a portfolio that will impress employers!
  • Навчання та стиль

КОМЕНТАРІ • 103

  • @PortfolioCourses
    @PortfolioCourses  2 роки тому +33

    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 роки тому

      @@zoquevil4792 You're welcome! 😀

    • @philipphortnagl2486
      @philipphortnagl2486 Рік тому

      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  Рік тому +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 8 місяців тому +5

    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.

  • @kuijaye
    @kuijaye 2 роки тому +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  2 роки тому

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

  • @withthehelp6291
    @withthehelp6291 2 роки тому +7

    This is exactly what I need for my Cs exam

  • @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 роки тому

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

  • @Rai_Te
    @Rai_Te 8 місяців тому +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.

  • @joeunderwood8973
    @joeunderwood8973 4 місяці тому

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

  • @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 роки тому +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
      ua-cam.com/video/Qp3WatLL_Hc/v-deo.html

    • @technicalgamer2565
      @technicalgamer2565 2 роки тому

      Thx man

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому

      You’re welcome! :-)

  • @MARCBOSCHMANZANO
    @MARCBOSCHMANZANO Рік тому +1

    You solve my problem! Lots of thanks🧡🧡

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

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

  • @patchavavengalraovengalrao3784
    @patchavavengalraovengalrao3784 2 роки тому +1

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

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому

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

  • @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 2 місяці тому

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

    • @PortfolioCourses
      @PortfolioCourses  2 місяці тому

      No, it's necessary in C++ but not C: ua-cam.com/video/KTbY4-chkcs/v-deo.html

    • @TheAcebyte
      @TheAcebyte 2 місяці тому

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

  • @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: ua-cam.com/video/ZLc_OpzND2c/v-deo.html. :-)

  • @bettyswunghole3310
    @bettyswunghole3310 2 місяці тому

    A very useful video! Thank you!

  • @arasunatesan1970
    @arasunatesan1970 6 місяців тому

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

  • @Walkingdeadman1991
    @Walkingdeadman1991 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.

    • @Walkingdeadman1991
      @Walkingdeadman1991 2 роки тому

      @@PortfolioCourses Cheers!

  • @sudhadevi6692
    @sudhadevi6692 Рік тому

    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  Рік тому

      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(): ua-cam.com/video/WXnWoRJ7WyU/v-deo.html.

  • @marcboschmanzano1642
    @marcboschmanzano1642 Рік тому

    Hello! What IDE do you use?

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

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

  • @justcurious1940
    @justcurious1940 9 місяців тому

    Nice video, Thanks.

  • @aliali-gg7xu
    @aliali-gg7xu Рік тому

    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  Рік тому

      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.

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

  • @paulpranshu
    @paulpranshu 11 місяців тому

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

    • @PortfolioCourses
      @PortfolioCourses  11 місяців тому +1

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

    • @ziwaang2250
      @ziwaang2250 10 місяців тому

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

  • @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. 🙂

  • @sukshithshetty4847
    @sukshithshetty4847 Рік тому

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

    • @PortfolioCourses
      @PortfolioCourses  Рік тому

      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.

  • @fifaham
    @fifaham Рік тому

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

  • @manethdulshan9449
    @manethdulshan9449 3 місяці тому

    Thank youuu

  • @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(): ua-cam.com/video/vr7qCQLrUt8/v-deo.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.

  • @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. :-)

  • @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

  • @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: ua-cam.com/video/Vp6OELK4gmo/v-deo.html. The rest of it may be covered by other videos like this one on File I/O Basics: ua-cam.com/video/HQNsriyMhtY/v-deo.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! :-)

  • @philipphortnagl2486
    @philipphortnagl2486 Рік тому

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

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +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 Рік тому

      @@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  Рік тому

      @@philipphortnagl2486 You're welcome! 🙂

  • @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: ua-cam.com/video/X-1qodkHCHo/v-deo.html. The array is not dynamic though, that's what I will make a future video on when I'm able to.

  • @svenbb4937
    @svenbb4937 5 місяців тому +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.

  • @sergioberezovski4865
    @sergioberezovski4865 Рік тому

    thanks for helping me finish my project for this semester ✅

    • @PortfolioCourses
      @PortfolioCourses  Рік тому +1

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

  • @wurbo3488
    @wurbo3488 10 місяців тому

    .

  • @technicalgamer2565
    @technicalgamer2565 2 роки тому

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

  • @eighteen7875
    @eighteen7875 2 роки тому

    nice bro! its very kind that ur helping ur subs

    • @PortfolioCourses
      @PortfolioCourses  2 роки тому +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…

  • @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.

  • @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);

  • @mefrefgiweuhef4808
    @mefrefgiweuhef4808 2 роки тому

    dude THANK U!!

  • @dhakad22klx
    @dhakad22klx Рік тому

    Helpful😍

  • @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. 🙂

  • @ninadgandhi9040
    @ninadgandhi9040 2 роки тому +1

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