Thread: Best way to store an input string

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    71

    Best way to store an input string

    I'm extremely rusty at C but is this the best way to store an input string into a char*?

    Code:
    int length = 100; //initial size
    Code:
    char * name = malloc(length * sizeof(char)); //allocate mem for 100 chars 
    int count = 0; //to keep track of how many chars have been used 
    char c; // to store the current char 
    
    while((c = getchar()) != '\n'){ //keep reading until a newline 
        if(count >= length) 
            name = realloc(name, (length += 10) * sizeof(char)); //add room for 10 more chars 
        name[count++] = c 
    }


    Is this a good way and what could be better?
    Last edited by workisnotfun; 09-16-2013 at 09:18 PM.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I'd use an automatic variable of char array[length], and fgets, then sscanf or getchar() (as you have done here), and be done with it. Note that you have not accounted for the (albeit slim) possibility that either malloc or realloc, might fail.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    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. How to store a user input string into dynamic array?
    By sethwb in forum C++ Programming
    Replies: 4
    Last Post: 04-25-2011, 04:48 AM
  2. Replies: 1
    Last Post: 04-08-2011, 11:22 AM
  3. How to use enumerators to store input
    By Rubiks14 in forum C++ Programming
    Replies: 4
    Last Post: 10-16-2005, 09:43 PM
  4. How to store all the input char into text include space ?
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 12-20-2001, 04:34 PM