Thread: string and malloc

  1. #1

    Arrow string and malloc

    I am trying to figure out how to take in a couple strings, then store them into a place in memory, then call that memory and put into a function, so that it can print all strings, I believe this is how malloc is used
    thanx vry

  2. #2
    Registered User biosx's Avatar
    Join Date
    Aug 2001
    Here is a trivial example:

    #include <stdio.h>
    #include <stdlib.h>
    void put_string(char *s);
        char *c;
        c = (char *)malloc(20 * sizeof(char));
        printf("Enter String: ");
        printf("The string you entered was:\n");
        return 0;
    void put_string(char *s) {
         while (*s != '\0')
               printf("%c", *s++);
    This is a trivial example in which you can do so many different ways. I just chose a quick way.

    I include <stdlib.h> for the use of the malloc() & system() functions, <stdio.h> for printf(), gets(), etc..

    char *c;
    c = (char *)malloc(20 * sizeof(char));
    This is how malloc() works. It first allocates an amount of memory specified, in this case: 20 units the size of a char. Then malloc returns a pointer to that space created. You then must type-cast the pointer returned to (char *) b/c since you used sizeof() it will return a type of size_t.

    Then gets() is a handy function that takes in characters until it has found a newline ('\n') character. It then stores that string (minus the '\n') into a pointer.

    Then our makeshift put_string() function is simple. Just write a function that takes a character pointer argument and then walk along the string printing each character in the string. Then printf() a '\n' and voila.

    NOTE: There is a function in the C standard library called puts() that does the exact same thing has our makeshift put_string.

    Have fun and I hoped this helped.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc string array
    By Tayls in forum C Programming
    Replies: 27
    Last Post: 10-27-2008, 02:53 PM
  2. malloc 1d string array
    By s_siouris in forum C Programming
    Replies: 3
    Last Post: 07-07-2008, 09:20 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. string handling
    By lessrain in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 07:36 PM