簡體   English   中英

訪問 c 中動態數組的每個元素

[英]Access each element of a dynamic array in c

我使用 VScode 作為我的 IDE。 所以我創建了一個數組,數組的每個元素都存儲了一個指向鏈表的指針。 我的代碼如下所示:

typedef struct AdjStopList
{
    char stopName[20]; //name of stop bus is equal or less than 20 characters
    int numOfAdjStp;   //number of adjacent stops to this stop
    struct BusAtStopList *buslist;  // store all the buses passing this stop in a linked list
    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;

typedef struct BusNetwork
{
    int nBusStop; //number of bus stops in the newwork
    struct AdjStopList **array;
} BusNetwork;

//create a new empty AdjBusStopList
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;
}

我嘗試使用 while 循環在stopName中為 stopName 分配"test"

BusNetwork *newBusNetwork(int n, const char *BusStops)
{
    newBN->array = malloc(n * sizeof(AdjStopList*)); 

    for (int i = 0; i < 10; i++)
    {
        newBN->array[i] = newAdjStopList();
        strcpy(newBN->array[i]->stopName, "test");
    }
        
    //rest of the function
}

然后當我在VScode中觀察變量(struct AdjStopList (**)[46])newBN->array時,似乎只有數組的第一個元素被正確處理,例如newBN->array[0]->stopNametest 數組的 rest 元素仍然具有隨機垃圾值,例如newBN->array[1]->stopName

誰能明白為什么會這樣?

通過malloc()分配的緩沖區的初始值是不確定的,使用 (indeterminate) 值會調用未定義的行為

您必須在使用它們之前初始化指針。

另請注意, newBN->array指向的數組元素是struct AdjStopList * ,因此sizeof(struct AdjStopList *)sizeof(newBN->array[0])應該相乘而不是sizeof(AdjStopList)

BusNetwork *newBusNetwork(int n, const char *BusStops)
{
    /* correct allocation size */
    newBN->array = malloc(n * sizeof(newBN->array[0])); 
    /* check if allocation succeeded */
    if (newBN->array == NULL) return NULL;

    /* make sure not to cause out-of-range access */
    for (int i = 0; i < n && i < 10; i++)
    {
        /* initialize the element */
        newBN->array[i] = malloc(sizeof(*newBN->array[i]));
        /* check if allocation succeeded */
        if (newBN->array[i] != NULL)
        {
            strcpy(newBN->array[i]->stopName, "test");
        }
    }
        
    //rest of the function
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM