简体   繁体   English

链表的数组实现

[英]Array Implementation of Linked List

Trying to implement linked list using arrays, list gets created but while printing the array gets messed up and prints garbage values 尝试使用数组实现链接列表,创建列表,但是在打印数组时弄乱了并打印垃圾值

I have used gdb to debug the issue, the array is properly formed just before printing. 我已经使用gdb调试了该问题,该数组在打印之前就已正确形成。 As soon as I print the array, it starts printing garbage values. 一旦我打印了数组,它就会开始打印垃圾值。

int MAX_SIZE=10;

int *head;
int end = -1;

void appendToList(int value){
    if (end == -1){
        int list[MAX_SIZE] = {0};
        head = list;
        *(head + end + 1) = value;
        end++;
    }
    else
    {
        *(head + end + 1) = value;
        end++;
    }

}

int main(){
    appendToList(1);
    appendToList(8);
    appendToList(3);
    appendToList(4);
    appendToList(5);

    std::cout<< head[0] << "\n";
    std::cout<< head[1] << "\n";
    std::cout<< head[2] << "\n";
    std::cout<< head[3] << "\n";
    std::cout<< head[4] << "\n";

    return 0;
}

It should print "1 8 3 4 5". 它应该打印“ 1 8 3 4 5”。 The output is like "1 8 0 0 42050", but that is wrong. 输出类似于“ 1 8 0 0 42050”,但这是错误的。

int list[MAX_SIZE] is a local variable. int list[MAX_SIZE]是局部变量。 It's lifetime extends to the end of the scope where it was declared. 它的生命周期一直延伸到声明它的作用域的末尾。 In this case, the array does not exist outside of the if-statement. 在这种情况下,该数组在if语句之外不存在。

head = list sets the pointer in static storage to point to the local array. head = list将静态存储中的指针设置为指向本地数组。 Once the array is destroyed (at the end of the if-statement block) the pointer no longer points to an object. 一旦数组被销毁(在if语句块的末尾),指针将不再指向对象。 It is said to be dangling. 据说是晃来晃去的。

Upon further calls to the function, as well as in main the program indirects through the dangling head pointer, and the behaviour of the program is undefined. 在进一步调用该函数以及main调用该函数时,该程序通过悬空的head指针进行间接调用,并且该程序的行为未定义。 To fix this, you must use an array whose lifetime extends for at least as long as it is being used. 要解决此问题,您必须使用其寿命至少可以延长的数组。

You should always be on your toes when a pointer / reference / iterator has longer lifetime than the object they are pointing to. 当指针/引用/迭代器的生存期比其指向的对象长时,您应该始终保持警惕。


PS Your array appears to have nothing to do with a linked list. PS您的阵列似乎与链接列表无关。

PPS The program is ill-formed because MAX_SIZE is not a compile time constant expression. PPS程序MAX_SIZE因为MAX_SIZE不是编译时间常数表达式。 The size of an array must be compile time constant. 数组的大小必须是编译时间常数。 To fix this, declare the variable either const or constexpr . 要解决此问题,请声明变量constconstexpr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM