![]() |
| | #1 |
| Registered User Join Date: Jul 2009
Posts: 10
| Storing Cstrings in an Array 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;
}
|
| Tien1868 is offline | |
| | #2 |
| and the Hat of Guessing 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 | |
| | #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 | |
| | #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 | |
| | #5 |
| and the Hat of Guessing 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 | |
![]() |
| Thread Tools | |
| Display Modes | |
|
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 |