我试图理解c ++中的指针和链表。为此,我写了一个小程序。我似乎很难通过curPtr查看列表,这似乎给了我列表中的所有初始元素,但不是我附加的元素。我不知道问题是什么。 这是我的主要功能:
int sizeOfLL = 5;
int* LLtail;
int* LLcur;
int* LLhead;
std::cout << "start values: " << (long long) LLhead << " " << (long long) LLcur << " " << (long long) LLtail << std::endl;
makeLListCstyle(LLhead, LLtail, sizeOfLL);
std::cout << "head in main(): " << (long long) LLhead << std::endl;
LLcur = LLhead;
std::cout << "cur in main(): " << (long long) LLcur << std::endl;
std::cout << "tail in main(): " << (long long) LLtail << std::endl;
for (int i = 0; i < sizeOfLL; i++){
LLcur[i] = 3*i;
}
//LLcur[3]=3;
appendElement(LLtail, 2);
std::cout << "tail in main(): " << (long long) LLtail << " value: " << LLtail[0] << std::endl;
sizeOfLL = getElementsInList(LLhead, LLtail);
std::cout << sizeOfLL << endl;
for (int i = 0; i < sizeOfLL; i++){
cout << "cur in main(): " << (long long) &LLcur[i] << " value: " << LLcur[i] << endl;
}
return 0;
这里是我的llist.hpp
void makeLListCstyle(int* &head, int* &tail, int numElements){
head = (int*) malloc(numElements * sizeof(int));
// std::cout << "sizeof(int): " << sizeof(int) << endl;
// std::cout << "head in makeLList(): " << (long long) head << std::endl;
tail = head + numElements; // points now at address which is sizeif(int) * numElements further in memory.
// std::cout << "tail in makeLList(): " << (long long) tail << std::endl;
// return head;
}
void appendElement(int* &tail, int newElement){
std::cout << "tail in appendElement(): " << (long long) tail << std::endl;
tail = tail+1;
std::cout << "tail in appendElement(): " << (long long) tail << std::endl;
// std::cout << "value of tail in appendElement(): " << (long long) *tail << std::endl;
*tail = newElement;
// std::cout << "value of tail in appendElement(): " << (long long) *tail << std::endl;
}
int getElementsInList(int* &head, int* &tail){
/*
std::cout << "head in getElementsInList(): " << (long long) head << std::endl;
std::cout << "tail in getElementsInList(): " << (long long) tail << std::endl;
std::cout << ( (long long)(tail) - (long long)(head) )/ sizeof(int) << endl;
*/
return ( (long long)(tail) - (long long)(head) ) / sizeof(int);
}
这里是输出。
cur in main(): 18857008 value: 0
cur in main(): 18857012 value: 3
cur in main(): 18857016 value: 6
cur in main(): 18857020 value: 9
cur in main(): 18857024 value: 12
cur in main(): 18857028 value: 0
最后一个应该是2而不是零。我在这做错了什么?
答案 0 :(得分:0)
在makeLListCstyle
功能中执行
tail = head + numElements;
这使tail
指向超出分配的内存。
所以当你做appendElement
tail = tail+1;
您将 您的代码基本上等同于 您所拥有的只是关闭到链接列表。你所拥有的只是一个动态分配的数组,你可以超出范围。tail
指向一个元素超出分配内存的末尾,当您写入此位置时会导致undefined behavior。< / p>
int LLHead[5];
// Initialize elements 0 to 4
LLHead[6] = 2;