C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 07-09-2009, 06:13 PM   #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
Tien1868 is offline   Reply With Quote
Old 07-09-2009, 06:49 PM   #2
and the Hat of Guessing
 
tabstop's Avatar
 
Join Date: Nov 2007
Posts: 8,740
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.
tabstop is offline   Reply With Quote
Old 07-09-2009, 06:57 PM   #3
Registered User
 
Join Date: Oct 2008
Location: TX
Posts: 1,262
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
itCbitC is offline   Reply With Quote
Old 07-09-2009, 07:40 PM   #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.
Tien1868 is offline   Reply With Quote
Old 07-09-2009, 07:48 PM   #5
and the Hat of Guessing
 
tabstop's Avatar
 
Join Date: Nov 2007
Posts: 8,740
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.
tabstop is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Storing an array of structures? Sparrowhawk C Programming 4 12-15-2008 03:07 AM
Class Template Trouble pliang C++ Programming 4 04-21-2005 04:15 AM
Template Array Class hpy_gilmore8 C++ Programming 15 04-11-2004 11:15 PM
Storing multiple string in array winsonlee C Programming 2 03-15-2004 07:49 AM
Help with an Array omalleys C Programming 1 07-01-2002 08:31 AM


All times are GMT -6. The time now is 07:14 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

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