Reputation: 45
So i was given a task to write a small print function to the linked list. I dont have any troubles with that(i guess), however i cannot create the list itself. I have tried allocating and linking the members of the list as soon as the user has entered their values, but i have got a lot of troubles assigning pointers to non existing members. So i have decided to get all the members` data at the beginning and link them after. The trouble i have right now is that for some reason when writing data to a dynamic array of structs the data is written only to the first member, although i dont have any errors and the syntax seems to look okaish.
Here is my code:
typedef int ELMNT;
typedef struct list
{
ELMNT element;
struct list * next;
}DLIST;
DLIST createList()
{
std::cout << "Enter the length of an array: ";
int arrLength;
std::cin >> arrLength;
int integer;
std::cin >> integer;
DLIST mylist;
mylist.element = 0;
mylist.element = integer;
DLIST* listptr = new DLIST[arrLength];
for (int i = 0; i < arrLength; ++i)
{
std::cin >> integer;
listptr[arrLength].element = integer;
}
for (int i = 0; i < arrLength; ++i)
{
std::cout << listptr[arrLength].element;
}
return mylist;
}
int main()
{
createList();
}
TL:DR:
Lines 3 to 8 are given by the task.
I need to create a dynamic linked list.
The problem is that listptr[arrLength].element = integer;
is not behaving as expected(not working at all). Any ideas? It seems to be some kind of syntax error or typo but i cannot solve it for and hour and a half.
EDIT:Oh thanks to the comments i see that next are not initialized when creating. How to do i initialize them? With NULL?
Upvotes: 0
Views: 42
Reputation: 88017
I don't know exactly why you are trying to do what you are doing, your code looks nothing like a linked list, but the errors are here
for (int i = 0; i < arrLength; ++i)
{
std::cin >> integer;
listptr[arrLength].element = integer;
}
should be
for (int i = 0; i < arrLength; ++i)
{
std::cin >> integer;
listptr[i].element = integer;
}
and (same error really)
for (int i = 0; i < arrLength; ++i)
{
std::cout << listptr[arrLength].element;
}
should be
for (int i = 0; i < arrLength; ++i)
{
std::cout << listptr[i].element;
}
Upvotes: 2
Reputation: 950
You wrote
listPtr[arrLength].element
Instead of listPtr[i].element
(In both the printing and the assignment)
BTW this is dynamic array, not a linked list.
Upvotes: 1