Thread: how to use malloc for array of strings

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    30

    how to use malloc for array of strings

    Hi all,

    how do i use malloc to allocate memory for an array of strings?

    can i write the code like this?
    Code:
    char *line = (char *)malloc(sizeof(char) * 100 * 100);
    line[0] = "how";
    line[1] = "are";
    line[2] = "you";
    ...

    Thanks...

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    First of all, typecasting the return value of malloc() is unnecessary. Secondly, you'll want line to be a pointer to a pointer of type char. Then you set line equal to enough allocated memory to hold the number of strings you want multiplied by the size of a pointer.
    If you understand what you're doing, you're not learning anything.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you want a hundred strings, then you need a hundred pointers. So you allocated that many pointers. Then you go through and loop and allocated space for each string.

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Your method will not produce the results you are wanting.

    Essentially here is what you now have in memory.

    Line []=
    howareyou......................................... ...........->((100x100)-9 bytes)

    Of course "how are you" would be in hex but you get the point. There is a way to properly store all strings in one huge linear array rather than using multiple indirection or a 2D array.
    Write a function that will append the null terminator to the end of a string. Put this string into array at the correct offset.

    Note that by doing this you will still run into trouble using the C library of functions for manipulating strings. Those functions will only test this string: "how" since the null terminator would be at the end of how. Also printf() would only print "how".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Wierd Malloc Problem
    By mohankarthik in forum C Programming
    Replies: 11
    Last Post: 09-17-2008, 02:14 PM
  2. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  4. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:34 AM
  5. malloc with arrays of strings
    By Lib in forum C Programming
    Replies: 2
    Last Post: 08-03-2003, 10:46 PM