Hey so im struggling hard. I need to create a random string (of length 2 to 6) and generate a random character for each one ‘A’ to ‘Z’. The problem is that I am trying to use a struct with a char* in it. then dynamically allocate each struct when i try to generate the random data.
struct TStruct
{
int ID;
float Value;
int a[4];
char *Name;
};
//create pointer to TSruct
typedef struct TStruct *ptrStruct;
//have ptrStruct point to 10 structs
ptrStruct structs[NUM_STRUCTS];
void genStruct(ptrStruct *alpha, int countID){
//declare variables
//ID counter
countID+=1;
int i;
int temp;
int tempChar;
int nameSize;
*alpha = (ptrStruct)malloc(sizeof(struct TStruct));
srand(time(0));
//put the ID in
(*alpha)->ID=countID;
//random number 0 to 999.99
(*alpha)->Value= (float)rand()/((float)(RAND_MAX)+1000)/100;
//store 4 ints 0 to 100 into array a
for (i = 0; i < 4; i++) {
//generate random number
temp = rand() % 100;
//put into the array
(*alpha)->a[i] = temp;
}
//generate a random length for the name 2 to 6
nameSize = rand() % 4 + 2;
char buffer[2];
//run a for loop based on the size of nameSize
//THIS IS THE PROBLEM CODE!!!
for (i = 0; i < nameSize; i++) {
snprintf(buffer,2, "%d",(rand() % 25)+65);
strcat((*alpha)->Name,buffer);
}
}
Any help would be sooooo appreciated.
thanks
One primary problem is that you don’t allocate space for the string. You have an uninitialized
char *Namein the structure.Frankly, for 6 (even 8) characters, you should simply allocate the array as part of the structure. On a 64-bit machine, the pointer would be bigger than the array; on a 32-bit machine, you’d still be using more space with a pointer plus data than with just the data.
Your character generation loop is wonky too. The
rand()expression is more or less reasonable (it won’t generate ‘Z’ and will be biassed towards the start of the alphabet), but you should use'A'instead of 65, and you should simply assign the character to the relevant position in the name. Usingsnprintf()like that will get you the 10’s digit of the code for each letter, which is not what you want at all.Don’t forget to null terminate the string. And don’t forget that
strcat()only works when the string is already null terminated; you haven’t fixed that, either.Joachim Pileborg made an accurate comment in a now deleted remark, that you should ensure you only call
srand()once, usually at program startup. If you call thegenStruct()function more than once in a second (and if you call it more than twice, you can pretty much guarantee that — even on an original IBM PC at 4 MHz — you will have at least two of the three calls in the same second) then you will get the same data generated each timesrand()is called with the same number (time).