Search code examples
cstringmallocdynamic-memory-allocationdynamic-arrays

How I can control the length of the string that I want to enter during runtime and then reallocate the memory to store larger string?


For example, I want to enter a string that can store only five elements. It can be "Hello", but if I enter more than 5 elements like "Hello World". It stores only the "Hello" part. And I want to control the size or the number of elements that I enter inside the string using the malloc() function. So that I can later change the size of the string using realloc() to store a much larger string like "Hello World" or concatenate the original string with a new string, just like we do by using the strcat() function.

I am new to C and English is not my first language. So, if there is any part that you don't understand, please let me know.

Is it possible?


Solution

  • For many applications simple use a large buffer ...

    #define LINE_SIZE 100  // Be generous in size
    char buf[LINE_SIZE];
    

    ... and read a line of user input with fgets().

    if (fgets(buf, sizeof buf, stdin)) {
      // Success!
    
      // If deisred, lop off potential trailing \n
      buf[strcspn(buf, "\n")] = '\0';
    

    After reading the line into a string, then parse the string for "the number of elements".

    You cannot control what a user types in. Code can control how it handles the input. Be prepared for incorrect, foolish and hostile input.


    Advanced: If you want unlimited length inputs (be careful what you wish for), more advanced strategies and code are needed to handle memory allocation/reallocation.