Thread: how to allocate memory space dynamically to display the string?

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    1

    how to allocate memory space dynamically to display the string?

    hi friends,

    I am just beginner for c programming am going to do a project using c .I need to allocate memory space dynamically to display the string mean to say is, if I give any string from user screen, it should allocate the space and also it has to print the string what I am going to give on user screen..So I need program with clear explanations as soon as possible, please help me out from this problem.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    I suggest you start by prototyping your ideas using a fixed length array.

    Changing a fixed array into a malloc'ed array is very easy, once the fixed array version is WORKING.

    But newbies can run into all sorts of problems trying to debug malloc based code, when they've got no idea whether it's a memory issue or something else which is causing the crashes.
    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.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Standard-library functions which read strings are designed to operate on pre-allocated arrays as Salem mentioned. Could you clarify what you mean by dynamically allocated? Do you mean the array should grow arbitrarily as the user types a string, even if she types in 100 megabytes of characters? If you can give a reasonable upper limit (which is usually a good idea anyway), then the approach mentioned above by Salem is optimal.

    static char buf[100000];

    // ...

    After you read into buf, then if you want you could allocate dynamically if you want to save that string for something else later.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. allocate memory for constant string?
    By slenkar in forum C Programming
    Replies: 4
    Last Post: 09-17-2012, 10:21 AM
  2. Dynamically allocate memory to create 2D array
    By nonlinearly in forum C Programming
    Replies: 15
    Last Post: 11-10-2011, 02:22 AM
  3. pre-allocate memory for string
    By TheBigOnion in forum C++ Programming
    Replies: 6
    Last Post: 03-30-2010, 01:10 PM
  4. Replies: 5
    Last Post: 03-23-2009, 03:44 PM
  5. allocate memory dynamically
    By rahulsk1947 in forum C++ Programming
    Replies: 3
    Last Post: 04-08-2007, 04:30 PM