Reputation: 37
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.
Upvotes: 0
Views: 88
Reputation: 3465
The type of newBN->array
is struct AdjStopList *
so the type of newBN->array[i]
is struct AdjStopList
but the return type fromnewAdjStopList()
is struct AdjStopList*
. So that should explain the error that you see where you are assigning a struct AdjStopList*
to struct AdjStopList
in the line
newBN->array[i] = newAdjStopList();
I believe you should change
typedef struct BusNetwork
{
int nBusStop; //number of bus stops in the newwork
struct AdjStopList *array;
} BusNetwork;
to
typedef struct BusNetwork
{
int nBusStop; //number of bus stops in the newwork
struct AdjStopList **array;
} BusNetwork;
So that array
becomes an array of pointers to struct AdjStopList
. Then that original assignment should work.
Upvotes: 1