Storing Cstrings in an Array

This is a discussion on Storing Cstrings in an Array within the C Programming forums, part of the General Programming Boards category; How would I go about storing ctrings in an array with a structure? Here is how it might look in ...

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    10

    Storing Cstrings in an Array

    How would I go about storing ctrings in an array with a structure? Here is how it might look in C++.
    Code:
    #define RANDOM_NUM		((float)rand()/(RAND_MAX+1))
    
    string	GetRandomBits(int length);
    
    using std::string;
    
    struct name
    {
          string str;
    }
    
    int main()
    {
    
    
            name array[20];
    for(int i=0; i<20; i++)
    {
             array[i].str= GetRandomBits(150);
    }
    }
    string	GetRandomBits(int length)
    {
    	string bits;
    
    	for (int i=0; i<length; i++)
    	{
    		if (RANDOM_NUM > 0.5f)
    
    			bits += "1";
    
    		else
    
    			bits += "0";
    	}
    
    	return bits;
    }
    Thanks

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    If you need full flexibility, then just store a char*. If you don't need, say, the ability to resize the string, then just use a char array.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    The thing is that C unlike C++ doesn't provide any operators for processing a string of characters as a unit. What you intend to do can be done by defining the struct to be an array of characters, as in
    Code:
    typedef struct {char str[100];} name

  4. #4
    Registered User
    Join Date
    Jul 2009
    Posts
    10
    I was referring more to the actual array assignment. I tried using strcpy() which didn't work. I think malloc() may help but I am not sure.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    If you use char* then malloc() is necessary. If you use char arrays then you are required to not use malloc. Either way strcpy does work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Storing an array of structures?
    By Sparrowhawk in forum C Programming
    Replies: 4
    Last Post: 12-15-2008, 02:07 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. Storing multiple string in array
    By winsonlee in forum C Programming
    Replies: 2
    Last Post: 03-15-2004, 06:49 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

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