Coming from some experience with Java/C#, I'm struggling to get my head around some parts of C. I have an array of structs. These structs, at the moment, have only one member (I'll be adding others down the track) - an array of chars. This array is a string of 6 characters - two letters, four digits (e.g. XY1234).
The follow code produces the objectCode I'm looking for:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define LETTERS_IN_ALPHABET 26
typedef struct object {
char objectCode[6];
} object_t;
void GetRandomSeed() {
srand((unsigned)time(NULL));
}
char RandomLetter() {
return 'A' + rand() % LETTERS_IN_ALPHABET;
}
int RandomDigit() {
return rand() % 10;
}
int main() {
GetRandomSeed();
object_t object1;
for (int i = 0; i < 2; i++) {
object1.objectCode[i] = RandomLetter();
}
for (int i = 2; i < 6; i++) {
object1.objectCode[i] = '0' + RandomDigit();
}
// Print objectCode string to screen
for (int i = 0; i < 6; i++) {
printf("%c", object1.objectCode[i]);
}
printf("\n");
return 0;
}
I'm trying to wrap the for loops (the ones randomly generating the code) in a function. However, the print out of my attempt to do this is just gibberish:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define LETTERS_IN_ALPHABET 26
typedef struct object {
char objectCode[6];
} object_t;
void GetRandomSeed() {
srand((unsigned)time(NULL));
}
char RandomLetter() {
return 'A' + rand() % LETTERS_IN_ALPHABET;
}
int RandomDigit() {
return rand() % 10;
}
void GenerateCode(object_t object) {
for (int i = 0; i < 2; i++) {
object.objectCode[i] = RandomLetter();
}
for (int i = 2; i < 6; i++) {
object.objectCode[i] = '0' + RandomDigit();
}
}
int main() {
GetRandomSeed();
object_t object1;
// Print objectCode string to screen
for (int i = 0; i < 6; i++) {
printf("%c", object1.objectCode[i]);
}
printf("\n");
return 0;
}
I'm bit of an infant when it comes to C so I really appreciate any help you can give. Thanks.