嘿,所以我在努力奋斗。我需要创建一个随机字符串(长度为 2 到 6)并为每个“A”到“Z”生成一个随机字符。问题是我正在尝试使用一个带有 char* 的结构。然后当我尝试生成随机数据时动态分配每个结构。
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);
}
}
任何帮助将不胜感激。谢谢