Re: Declare a 2D Dynamic array
Quote:
Originally Posted by
laserlight
I get these errors when trying to compile your sample program with the MinGW port of g++ 3.4.5:
Code:
test.cpp:1: error: `rand' was not declared in this scope
test.cpp:6: error: expected unqualified-id before "for"
test.cpp:6: error: expected constructor, destructor, or type conversion before '<' token
test.cpp:6: error: expected constructor, destructor, or type conversion before '++' token
Of course, you can point out to me that I was expected to #include <cstdlib> and place your code snippet in a main function, but I
did ask for a compilable program ;)
Anyway, a possible problem is that you are using the same value (asciival) on every iteration. You probably want to do this instead:
Code:
#include <iostream>
#include <cstdlib>
#include <limits>
// Generate a portable seed based on system time.
unsigned int timeSeed()
{
using namespace std;
time_t now = time(0);
unsigned char* p = reinterpret_cast<unsigned char*>(&now);
unsigned int seed = 0;
unsigned int seed_multiplier = numeric_limits<unsigned char>::max() + 2U;
for (size_t i = 0; i < sizeof now; ++i)
{
seed = seed * seed_multiplier + p[i];
}
return seed;
}
int main()
{
using namespace std;
srand(timeSeed());
char a[4][5];
for(int i=0; i<4; i++)
{
for(int j=0; j<5; j++)
{
a[i][j] = (rand() % 26) + 'a';
cout<<a[i][j];
}
cout<<endl;
}
}
The timeSeed() function is just some code I adapted from this tutorial on
using rand().
Thanks, by any chance is there a less complicated procedure I could follow to generate a random alphabet matrix? because at this point I really don't understand this function much, Thanks!!
Re: Declare a 2D Dynamic array
Quote:
Originally Posted by Elite Commando
Thanks, by any chance is there a less complicated procedure I could follow to generate a random alphabet matrix? because at this point I really don't understand this function much, Thanks!!
Read the tutorial I linked to. If you want, you could just resort to:
but the main part of the fix has to do with this line:
Code:
a[i][j] = (rand() % 26) + 'a';
That said, note that strictly speaking the letters after 'a' in the alphabet are not required to actually come after 'a' in the character set, but in practice this is usually the case since ASCII or a variant thereof is used.