I am learning pointers these days and while learning generic pointers I came across an issue that if I want to increment the pointer value in a loop for both char and int***, how exactly can I do it. I can increment the pointer easily while dealing with one data type but in the following code, I want to increment the pointer value for both int and char.
while running the code I get the segmentation fault: 11 error message.
#define SIZE 3
enum type_details {is_book, is_article};
typedef struct library
{
enum type_details type;
void *item;
}library;
typedef struct item_details
{
char *title;
int pages;
}item_details;
int main(void)
{
item_details details[SIZE];
library library;
// input title and pages values for three books
details[0].title = malloc(SIZE*10);
details[0].title = "C++";
details[0].pages = 200;
// book 2
details[1].title = malloc(SIZE*10);
details[1].title = "Java";
details[1].pages = 300;
//book 3
details[2].title = malloc(SIZE*10);
details[2].title = "Python";
details[2].pages = 400;
// displaying values through normal mechanism
for (int i = 0; i < SIZE; i++)
{
printf("item: %i, Book %s with %i pages\n",i , details[i].title, details[i].pages);
}
// Displaying values using void pointer
library.item = details;
for (int i = 0; i < SIZE; i++)
{
printf("item: %i, Book %s with %i pages\n",i ,*(char**)library.item, *(int*)library.item);
library.item = (int*)library.item + 1; // error lies here
library.item = (char**)library.item + 1; // and here
}
free(details[0].title);
free(details[1].title);
free(details[2].title);
return 0;
}