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. 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". The output is like "1 8 0 0 42050", but that is wrong.
int list[MAX_SIZE] = {0};gets destructed after going out of scope.listarray in your function is local. Once the scope it's defined in ends, so does the life-time of thelistarray. Any pointer you have to it will become invalid.int list[MAX_SIZE] = {0};initializes only the first element of the array.