I am trying to create a dynamic array to store a linked list in each element of the array. So I defined the linked list structure as below:
//data type for adjacent bus stop
typedef struct AdjStopNode
{
int distance; //travel distance from the bus original stop to this adjcent stop
int stopID;
struct AdjStopNode *prev; //pointer to previous bus stop
struct AdjStopNode *next; //pointer to next bus stop
} AdjStopNode;
AdjStopNode *newAdjStopNode(int distance, int stopID)
{
AdjStopNode *newNode = (AdjStopNode *)malloc(sizeof(AdjStopNode));
assert(newNode != NULL);
newNode->distance = distance;
newNode->stopID = stopID;
newNode->next = NULL;
return newNode;
}
typedef struct AdjStopList
{
char stopname[20];
int numOfAdjStp;
struct BusAtStopList *buslist;
struct AdjStopNode *first; //pointed at the first AdjBusStop of the linked list
struct AdjStopNode *last; //pointed at the first AdjBusStop of the linked list
} AdjStopList;
AdjStopList *newAdjStopList()
{
AdjStopList *newList = (AdjStopList *)malloc(sizeof(AdjStopList));
newList->buslist = newBusAtStopList();
assert(newList != NULL);
memset(newList, NULL, 20 * sizeof(newList[0]));
newList->first = NULL;
newList->last = NULL;
newList->numOfAdjStp = 0;
return newList;
}
Then I defined a dynamic array to store each AdjStopList as an element of the array is as below:
typedef struct BusNetwork
{
int nBusStop; //number of bus stops in the newwork
struct AdjStopList *array;
} BusNetwork;
My function to assign an empty AdjStopList to every element of the array is as below:
//n is the number of AdjStopList
void listToArray(int n)
{
BusNetwork *newBN;
newBN = malloc(sizeof(BusNetwork));
assert(newBN != NULL);
newBN->nBusStop = n;
newBN->array = malloc(n * sizeof(AdjStopList)); //create an array of n number of dejacency lists
for (int i = 0; i < n; i++)
{
newBN->array[i] = newAdjStopList();
}
}
The above code gives me the error at newBN->array[i] = newAdjStopList() as
a value of type "AdjStopList *" cannot be assigned to an
entity of type "struct AdjStopList" C/C++(513)
using VScode.
Could someone help me to fix this problem and explain to me why? Much appreciated.
BusNetworkstructure memberarrayis an "array" ofAdjStopListstructure objects. ThenewAdjStopListfunction returns a pointer to aAdjStopListstructure object.struct AdjStopListversusstruct AdjStopList *.listToArrayis wrong...newBNis never returned.... so all it does is to leak memorymemset(newList, NULL, 20 * sizeof(newList[0]));looks strange... what do you expect this to do?