Question

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.

Was it helpful?

Solution 2

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!' */

OTHER TIPS

You are looking for "pointer arithmetic".
In you example, you are allocating 10 bytes of memory, and store the address of the first byte in the pointer str.
Then you copy the string "hello" to this memory, which leaves you 4 bytes you can use (because "hello" is 5 bytes + one byte for the string termination character \0).
If you want to store something in those remaining 4 bytes, you can just calculate the memory address with pointer arithmetic. For example, if you want to access the 6'th byte from str, you do str+5. simple.
So, to extend your example, you can do:

strcpy(str, "Hello");
strcpy(str+5, " man");

and the output of printf("String is %s\n", str); would be "Hello man".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top