I'm working on an assignment of creating a "cat" database using a struct to record the name, gender, weight etc. of cats using C. I have made a few header files below:
Cat.h
#pragma once
#include <stdint.h>
const int MAX_CAT_NAME = 50;
enum Gender {
MALE,
FEMALE,
UNKNOWN
};
struct Cat{
char name[MAX_CAT_NAME + 1];
Gender gender = UNKNOWN;
float weightInPounds = 0.01;
uint32_t chipId = 0;
bool isFixed = false;
};
ArrayDB.h
#pragma once
#include "Cat.h"
#define MAX_CATS 100
extern Cat catArray[ MAX_CATS ];
extern int* numCats;
and ArrayDB.c
#include "ArrayDB.h"
#include "Cat.h"
Cat catArray[ MAX_CATS ];
void initDB() {
*numCats = 0;
for( int i = 0; i < MAX_CATS; i++ ) {
Cat Cat = generateCat();
if( validateCat(&Cat) ) {
catArray[ numCats++ ] = Cat;
}
}
}
There is also a Cat.c
file I have linked with struct Cat to generate the cat's name, validate the cat and print the cat, but I'm not sure if it is needed to initialize the database
In my assignment instructions, I was told for the header file, ArrayDB.h
:
ArrayDB.h
ArrayDB.h
ArrayDB.h
I've done this, but I'm stuck on the next step for ArrayDB.c:
"Define all three declarations in ArrayDB.c
(I hope I've done this correctly) and write a function called initDB in ArrayDB.c to initialize the database." The return type and parameters were left up to me, so I just used a void function.
In my code for ArrayDB.c
, I've attempted to call the functions that I've written from Cat.c
(That also uses variables from struct Cat) to initialize the "cat" database, but I have compilations errors in ArrayDB.c
that say generateCat and validateCat() are undeclared. I thought if I included the header file from Cat.h
, I'd be able to initialize the database, but I think this isn't how I can do this.
Can someone show me how I can initialize the database in my function void initDB()?
I thought I can do it with my header files, but I'm not sure now.
I can paste my Cat.c
code if it's needed. I would appreciate any guidance.
In C you initialize variables (instance of a type) not the type struct Cat
which is syntax error. You also want to use a symbolic constants (#define) instead of a const variable
. You are missing typedefs for Gender
and Cat
to be able to use them the way you do.
I suggest you avoid using global variables so you define your database in main() instead:
If you generate an instance of struct Cat
there should be no need to validate them.
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_CATS 100
#define MAX_CAT_NAME 50
enum Gender {
MALE,
FEMALE,
UNKNOWN
};
struct Cat {
char name[MAX_CAT_NAME + 1];
enum Gender gender;
float weightInPounds;
uint32_t chipId;
bool isFixed;
};
void initDB(struct Cat cats[MAX_CATS]) {
for(size_t i = 0; i < MAX_CATS; i++ )
cats[i] = (struct Cat) { "", UNKNOWN, 0.01, 0, 0 };
}
int main() {
struct Cat cats[MAX_CATS];
initDB(cats);
}