string and malloc

This is a discussion on string and malloc within the C Programming forums, part of the General Programming Boards category; I am trying to figure out how to take in a couple strings, then store them into a place in ...

  1. #1
    vei
    Guest

    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
    Posts
    230
    Here is a trivial example:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void put_string(char *s);
    
    main()
    { 
        char *c;
    
        c = (char *)malloc(20 * sizeof(char));
    
        printf("Enter String: ");
        gets(c);
    
        printf("The string you entered was:\n");
        put_string(c);
    
        system("PAUSE");
        return 0;
    }
    
    void put_string(char *s) {
    
         while (*s != '\0')
               printf("%c", *s++);
    
         printf("\n");
    }
    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..

    Code:
    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, 03:53 PM
  2. malloc 1d string array
    By s_siouris in forum C Programming
    Replies: 3
    Last Post: 07-07-2008, 10: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, 08:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21