Search code examples
cmallocdynamic-arrayscallocdynamic-allocation

Using malloc() for multiple inputs?


Alright I know that malloc or calloc can be used for dynamic allocation but as a new to C I don't know how to use that memory I allocated for inputting multiple inputs like in example of TC++ we have this code

#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <process.h>

int main(void)
{
   char *str;

   /* allocate memory for string */
   if ((str = (char *) malloc(10)) == NULL)
   {
      printf("Not enough memory to allocate buffer\n");
      exit(1);  /* terminate program if out of memory */
   }

   /* copy "Hello" into string */
   strcpy(str, "Hello");
    /* display string */
    printf("String is %s\n", str);
    /* free memory */
   free(str);

   return 0;
}

In thus code we place Hello to memory we allocated now that should leave us with 4 more character spaces what we should do to add data to those spaces as well.

I want to implement this idea when the user is asked about number of inputs and he lets say 10 or 100 then the program inputs the data and stores them and print that data to screen.


Solution

  • If you want to append to your malloced string, use strcat

    str = malloc(20);
    ...
    /* copy "Hello" into string */
    strcpy(str, "Hello");
    strcat(str, ", world!");
    /* display string */
    printf("String is %s\n", str); /* will print 'Hello, world!' */