I am trying to create an array of pointers that points to another array of structs. However, I am confused as to whether I should declare the new array as an int or the same type as the first array since it is going to hold pointers. This is what I have so far:
struct inventoryItem
{
int itemNumber;
int itemsInStock;
float cost;
float retailPrice;
};
int main()
{
printf("Enter the number of slots needed in the array: ");
int size;
scanf("%d", &size);
//array of items
struct inventoryItem *inventory; //use pointer to item
inventory =(struct inventoryItem *) malloc(sizeof(struct inventoryItem)*size); //create array to store inventoryItem with size 'size'
//array of index
//int *indexArray = (int*) malloc(sizeof(int)*size);
struct inventoryItem *indexArray; //use pointer to item
indexArray =(struct inventoryItem *) malloc(sizeof(struct inventoryItem)*size); //create array to store inventoryItem with size 'size'
//fill array contents
for(int i = 0; i < size; i++)
{
printf("Enter item %d number: ", i);
scanf("%d", &inventory[i].itemNumber);
printf("Enter item %d stock: ", i);
scanf("%d", &inventory[i].itemsInStock);
printf("Enter item %d cost: ", i);
scanf("%f", &inventory[i].cost);
printf("Enter item %d price: ", i);
scanf("%f", &inventory[i].retailPrice);
}
for(int i = 0; i < size; i++)
{
printf("Item %d number: %d\n", i, inventory[i].itemNumber);
printf("Item %d stock: %d\n", i, inventory[i].itemsInStock);
printf("Item %d cost: %f\n", i, inventory[i].cost);
printf("Item %d retail price: %f\n", i, inventory[i].retailPrice);
}
//struct inventoryItem *header = inventory;
//struct inventoryItem *ptr = inventory;
for(int i = 0; i < size; i++)
{
indexArray[i] = &inventory[i];
//problem here, it says "no operator '=' matches these operands"
}
}
EDIT: Now that I created the array, how can I print the content of inventory using indexArray?