Here is it possible to assign int array to the int *itemsPurchased pointer? If it is possible how print the values?
Yes we can assign an array to a pointer as array is a constant pointer and reverse is invalid.
But this assignment should be used very carefully as array will be a stack variable and scope of the variable should be taken care before accessing this structure pointer
Also this method can be preferred over the dynamic memory allocation where memory fragmentation is a concern by malloc and free and we can avoid the dynamic allocation overhead.
Following is the code for this and output of print value in the array:
#include <stdio.h>
typedef struct KnightsMartSale {
char firstName[21];
char lastName[21];
int numItemsOnList;
int *itemsPurchased; // array of item numbers
struct KnightsMartSale *next;
} KMSale;
int main() {
KMSale sale;
int iPos = 0;
int Array[] = {1, 2, 3, 4, 5};
sale.numItemsOnList = sizeof(Array) / sizeof(Array[0]);
sale.itemsPurchased = Array;
for (iPos=0; iPos < sale.numItemsOnList; iPos++) {
printf("sale %d: %d\n", iPos, sale.itemsPurchased[iPos]);
}
return 0;
}
output:
sale 0: 1
sale 1: 2
sale 2: 3
sale 3: 4
sale 4: 5
malloced array.