嘿所以即時通訊苦苦掙扎。我需要創建一個隨機字符串(長度爲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);
}
}
任何幫助將sooooo讚賞。 謝謝
你忘了問一個問題.... – 2012-04-10 05:17:04
我無法創建隨機的名稱,我不知道問題是什麼或真的如何問它 – 2012-04-10 05:23:36