Другие ответы прекрасны, но только потому, что ваш код находится в C, это не значит, что он не может быть на C ++!
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define SIZE 256
struct Base {
int isbn;
char name[SIZE];
int year;
};
struct Book {
struct Base base; // Inheritance, C style
int number;
};
struct Magazine {
struct Base base; // Inheritance, C style
char author[SIZE];
};
/*
You're going to need to cast the arguments and return value.
Also provide the size of the element.
However: the code is generic, casting always works (if `Base` is the first element) , and there is no need for IF or SWITCH statements.
*/
struct Base* search(struct Base* array,int length,size_t size,int key){
for (int i=0;i<length;++i){
if (array->isbn == key){
return array;
}
// array[i] won't work, because the size of Base is not the size we need to jump in.
array = (struct Base*)((uint8_t*)array + size);
}
return NULL;
}
int main(int argc,char** argv){
// Initialize some data
struct Book books[] = {
{ {123,"Moby Dick",1851},1 },
{ {124,"Oliver Twist",1837},2 }
};
struct Magazine magazines[] = {
{{ 125,"Wired",2020 }, "Some author"},
{{ 126,"Byte",1990 }, "Some author"}
};
// Search for a book and a magazine
struct Book* book = (struct Book*)search((struct Base*)books,2,sizeof(struct Book),124);
struct Magazine* magazine = (struct Magazine*)search((struct Base*)magazines,2,sizeof(struct Magazine),126);
if (book){
printf("Found book %s, number: %d\n",book->base.name,book->number);
}
if (magazine){
printf("Found magazine %s, author: %s\n",magazine->base.name,magazine->author);
}
}