Thread: Input

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    8

    Input

    Hi
    I am trying a thing. in that i want to get lines of text which has special chars,numbers and chars and i dont want to allocate memory at the beginning. i want to allocate memory exactly needed for the input given.i dont want to waste memory.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    OK, so do it.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    58
    i dont want to waste memory.
    You can do it but it wastes time by only allocating the memory needed. That's a lot of calls to realloc.
    Code:
    char *getline(void)
    {
        char *s = NULL;
        int n = 0;
        int ch;
    
        do
        {
            ch = getchar();
            s = (char*)realloc(s, n + 2);
            s[n++] = ch;
        }
        while ( ch != '\n' );
    
        s[n] = '\0';
    
        return s;
    }
    If you want it to be fast you have to waste memory somewhere. Something like an array that holds parts of the string so you can use fread or fgets and call realloc less often.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Use a temp buffer (typically BUFSIZ in size) to read a line.
    Measure it's length, then allocate that much space, copy the line and save for later.
    Repeat until done.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem grabbing k/b input
    By falcon9 in forum C Programming
    Replies: 2
    Last Post: 10-28-2007, 11:47 AM
  2. continues input
    By Matty_Alan in forum C Programming
    Replies: 2
    Last Post: 06-22-2007, 10:04 PM
  3. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  4. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  5. Simple Console Input for Beginners
    By jlou in forum C++ Programming
    Replies: 0
    Last Post: 06-21-2005, 01:50 PM