this is my first post on Stack Overflow :)
Sorry if I seems egoistic, but I have an exam tomorrow and I'm facing a problem that I cannot solve. Hope to find here an answer, I tried to find out if there was already an opened 3d, but I cannot find it.
Here's my problem:
I'm writing a code in C++, using the pointer. Because of I retrieve always the same error on a larger code, I tried with an easier one, but the error persists.
The code is the following:
#include <iostream>
using namespace std;
struct EXAMPLE {
int value;
EXAMPLE *next;
};
int insertnew(EXAMPLE *&sorting, EXAMPLE val);
int printlist(EXAMPLE *&sorting);
int main() {
int i;
EXAMPLE new;
EXAMPLE *list = NULL;
for (i = 0; i < 3; i++)
{
cout << "value: " << endl;
cin >> new.value;
insertnew(list, new);
}
printlist(list);
system("Pause");
return 0;
}
int insertnew(EXAMPLE *&sorting, EXAMPLE val){
EXAMPLE *temp;
temp = new EXAMPLE;
temp->value = val.value;
temp->next = sorting;
sorting = temp;
return 0;
}
int printlist(EXAMPLE *&sorting) {
while (sorting != 0)
{
sorting = sorting->next;
cout << sorting->next << " " << sorting->value << endl;
}
return 0;
}
It's an easy LIFO structure.
I get a bad reading access error on this line:
cout << elenco->next << " " << elenco->valore << endl;
But here's the curios thing.
If I revert the lines in this way:
int printlist(EXAMPLE *&sorting) {
while (sorting != 0)
{
cout << sorting->next << " " << sorting->value << endl;
sorting = sorting->next;
}
return 0;
}
as a FIFO structure, I got no error at all!
Can you help me understanding where the problem is?
Thanks in advance
//edit
Uops, find out my error.
The while was supposed to be a recursive function, dunno why I inserted a while, assuming it will function as a recursive function.
just solved
cout << lista->value << endl;
while (list != NULL)
{
list = list->next;
if (list != 0) {
cout << list->value << endl;
}
}
Sorry
Let's take a look at your example code:
int printlist(EXAMPLE *&sorting) {
while (sorting != 0) //As long as "sorting" is not null
{
sorting = sorting->next; //Set "sorting" to the next value
cout << sorting->next << " " << sorting->value << endl; //print the value
}
return 0;
}
Just play this code through if you have only one element in your LIFO list.
int printlist(EXAMPLE *&sorting) {
while (sorting != 0) //"sorting" is not null
{
sorting = sorting->next; //Set "sorting" to the next value, which is null
cout << sorting->next << " " << sorting->value << endl; //crash because "sorting" is null
}
return 0;
}
This will happen every time you hit the last element.
You can change your code to a do-while-loop with an additional if, or add an if with a break within your current loop. But I would recommend to go with a for-loop on this one.
Also you don't need to pass the pointer by reference. You even shouldn't do it, as you don't want to change your list when printing it (as your current code does...)
How about something like this:
int printlist(EXAMPLE * sorting) {
for (EXAMPLE * current = sorting; current != 0; current = current->next)
{
cout << current << " " << current->value << " -> " << current->next << endl;
}
return 0;
}
I also changed the output a little bit to show more interesting data.
You are trying to access the tail of the list when sorting->next reaches the last element. With the second code you access only list elements.
Clear, thanks
I also tried another version
int printlist(EXAMPLE *list) {
if (list != NULL)
{
cout << list->value << "-> " << list->next << endl;
printlist(list->next);
}
return 0;
}
and this is how it was supposed to work from the beginning. In this way by just switching the two rows inside the IF I can change from LIFO to FIFO :)
Related
I am trying to make a mask delivery, ordering service code.
The function order will add a new order to order list.
The function output will output the list from newest to oldest order.
The function deliver removes the oldest order.
The following is the code:
#include <iostream>
#include <string>
using namespace std;
struct Mask {
string type;
string customer;
Mask *next;
};
void order(Mask *&head, string type, string customer){
cout << "Ordering " << type << " for " << customer << endl;
Mask *oldHead = head;
head = new Mask;
head->type = type;
head->customer = customer;
head->next = oldHead;
}
void output(Mask *head){
cout << "Outputting order list " << endl;
for (Mask *p = head; p != NULL; p = p->next)
cout << " " << p->type << " for " << p->customer << endl;
}
void deliver(Mask *&head){
if (head->next == NULL){
cout << "Delivering " << head->type;
cout << " for " << head->customer << endl;
delete head;
}
else
deliver(head->next);
}
int main()
{
Mask *head = NULL;
order(head, "3M-N95", "Alice");
order(head, "OxyAir", "Burce");
order(head, "3M-N95", "Cindy");
output(head);
deliver(head);
output(head);
}
Everything runs smoothly, but it says segmentation error(core dumped) at the end. I tried adding this:
if (head->next->next == NULL){
deliver(head->next);
head->next == NULL;
}
But the problem still exists. Any help is appreciated.
I changed deliver to this:
void deliver(Mask *&head){
if (head->next->next == NULL){
cout << "Delivering " << head->next->type;
cout << " for " << head->next->customer << endl;
head->next = head->next->next;
delete head->next;
}
else
deliver(head->next);
}
Apparently, just setting the pointer to NULL does not fix the problem, so I just updated it so that the second last pointer pointed directly to the end.
in "deliver" you force the function to meet the condition if(head->next == NULL)
and then trying to reach head->next->next which is like trying to say null->next (resulting with segmentation fault).
I would recommend traversing to the last "Mask" object with a while loop instead of using all those "if" statements which lead to the same result, or at least change the second if to else if in order to avoid meeting this "if" again.
I am attempting to solve a problem to improve my C++ skills. I have come across some unusual behavior and I am not sure why it is happening.
I initially parsed the stdin and sorted it into a map with a key and a matching element (value). I then want to read a list of keys and output the element (value). However, for some of the key names it returns the correct value but for others it does not, but, if I hard code the intended key it works.
I know I am parsing correctly since the correct key and value are in the map as shown at the end of my output.
I assume it is an issue with reading stdin since the boolean str.compare("tag1.tag2~name") == 0 never evaluates to 0.
The code is as follows:
//'it' is the name of my map
//q = 3
for (int i = 0; i < q; i++)
{
getline(cin, str);
if (str.compare("tag1.tag2~name") == 0)
{
cout << "key is found" << endl;
}
else
{
cout << "'" << str << "'" << endl;
}
if (it.count(str) == 0)
{
cout << "Not Found!" << endl;
}
else
{
cout << it[str] << endl;
}
}
map<string, string>::iterator ptr;
cout << "\nThe map it is : \n";
cout << "\tKEY\tELEMENT\n";
for (ptr = it.begin(); ptr != it.end(); ++ptr) {
cout << '\t' << ptr->first
<<"\t" + ptr->second << "\n";
}
return 0;
The output is:
'tag1.tag2~name
Not Found!
'tag1~name
Not Found!
'tag1~value'
HelloWorld
The map it is :
KEY ELEMENT
tag1.tag2~name Name1
tag1~value HelloWorld
The input is :
tag1.tag2~name
tag1~name
tag1~value
Thank you! I have been struggling with this for a while.
This is for a lab I have done, which is to create a simple queue using C++.
#include "Task5.h"
#include <iostream>
using namespace std;
void push(const long &i, node* &n) {
if (n == NULL) {
node *ptr = new node;
ptr -> item = i;
ptr -> next = NULL;
n = ptr;
cout << "Created New Node." << endl;
}
else {
node *ptr = n;
cout << "Created Pointer" << endl;
while (ptr -> next != NULL){
cout << "Finding Next..." << endl;
ptr = ptr -> next;
}
cout << "I'm here." << endl;
node *temp = new node;
temp -> item = i;
ptr -> next = temp;
cout << "Node Created." << endl;
}
}
long pop(node* &n) {
if (n == NULL) cout << "HEY!!! Can't pop an empty queue." << endl;
else {
long val;
node *ptr = n;
n = n -> next;
val = ptr -> item;
delete ptr;
return val;
}
}
int main() {
node *head = NULL;
push(13,head);
push(10,head);
push(18,head);
push(22,head);
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
}
This is giving the following output:
Created New Node.
Created Pointer
I'm Here.
Node Created.
Created Pointer
Finding Next...
I'm here.
Node Created.
Created Pointer
Finding Next...
Finding Next...
I'm here.
Node Created.
13
10
18
22
HEY!!! Can't pop an empty queue.
6296192
HEY!!! Can't pop an empty queue.
6296192
So the end result is that the code works, HOWEVER it outputs 6296192 randomly. I thought maybe I misspell something or cout is converting endl; to hex. My lab instructor also has no idea what's happening. Can someone tell me what is happening? If it helps, I am running this code via Linux-run terminal.
Thanks in advance.
In your function:
long pop(node* &n) {
you don't return anything in case of n == NULL is true. So this is UB, and might also cause such random values in output.
I'd suggest using the debugger with a breakpoint on the first cout << pop(head) << endl; and watch the value returned from pop each time.
Also the compiler is probably giving you a warning about the cause of the issue, always pay attention to the warnings it usually means something unintended will happen.
The cout << pop(head) << endl; uses the value returned by pop() but in the case of an empty queue there is no value returned, resulting in undefined behavior.
I've been coding for a few hours today but seem to have thrown a blank. The assignment is creating a grocery list and adding in certain items to it while checking to see if the item is already in the list, if the list is empty and other things.
While working on the assignment, I can't find the proper value/variable to use in my insert function and it's killing me that something this small has stopped me from doing the assignment. The error is in my GroceryList.cpp file where all the functions are defined and all the code written out so that it removes, inserts, and checks for empty list. Everything else seems to compile just fine so far (I still need to fix some functions) but right now I'm trying to get my insert function to work. Can anyone look over my code and point me in the right direction for which value to use in my insert function? Did I even write the insert function properly? Thanks.
GroceryList.h
#ifndef GROCERYLIST_H
#define GROCERYLIST_H
#include <string>
using namespace std;
namespace CS151GroceryList
{
// node definition
struct ListNode
{
string item;
ListNode *link;
};
// define a type for pointers to nodes
typedef ListNode* ListNodePtr;
// define the GroceryList class
class GroceryList
{
public:
// default constructor initializes an empty list
GroceryList();
// destructor - destroys the list and returns all memory to the heap
~GroceryList();
// returns true if the list is empty; false otherwise
bool empty();
// check to see if an item is in the list. If so, return true. If not, return false.
bool inList(const string& an_item);
// prints all of the items in the list. If insert is implemented correctly, the contents
// of the list will be printed in alphabetical order with no repeats.
void print();
// if an_item is found, remove it from the list
void remove(const string& an_item);
// put a new item into the list. The item should be placed into the correct
// position in the list. If the item is already in the list, no change is
// made to the list. Note, you should put A COPY of an_item into the list
void insert(const string& an_item);
private:
ListNodePtr top;
};
} // end CS151GroceryList namespace
#endif GROCERYLIST_H
GroceryListTest.cpp This test the functions to make sure they work. Adds in specific grocery items to the list, spits out the list, and removes what is in the list. Problem not here
#include <iostream>
#include <string>
#include "GroceryList.h"
using namespace std;
using namespace CS151GroceryList;
int main()
{
GroceryList mylist;
/**********************************************************************
* List insertion test *
**********************************************************************/
cout << "Inserting items into the grocery list." << endl << endl;
mylist.insert("Eggs");
mylist.insert("Bananas");
mylist.insert("Wheat Bread");
mylist.insert("Peanut Butter");
mylist.insert("Milk");
mylist.insert("Apples");
mylist.insert("White Bread");
cout << "Finished inserting items." << endl;
cout << "Grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl;
/**********************************************************************
* inList test *
**********************************************************************/
cout << "Testing in list functionality:" << endl;
if (mylist.inList("Oranges"))
{
cout << "Oranges are on the list." << endl;
}
else
{
cout << "Oranges are not on the list." << endl;
}
if (mylist.inList("Apples"))
{
cout << "Apples are on the list." << endl;
}
else
{
cout << "Apples are not on the list." << endl;
}
if (mylist.inList("Peanut Butter"))
{
cout << "Peanut Butter is on the list." << endl;
}
else
{
cout << "Peanut Butter is not on the list." << endl;
}
if (mylist.inList("White Bread"))
{
cout << "White Bread is on the list." << endl;
}
else
{
cout << "White Bread is not on the list." << endl;
}
/**********************************************************************
* List removal test *
**********************************************************************/
cout << "Testing list removal." << endl;
cout << endl << "I decided that I didn't want apples after all. Removing apples." << endl;
mylist.remove("Apples");
cout << "After removing apples, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
cout << endl << "I decided that I didn't want white bread either. Removing white bread." << endl;
mylist.remove("White Bread");
cout << "After removing white bread, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
cout << endl << "I'm lactose intolerant, I'd better not get milk. Removing milk." << endl;
mylist.remove("Milk");
cout << "After removing milk, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
}
GroceryList.cpp The error is in this file
To be exact the error is in this portion of the code. This is where each function gets called and all the inserting, removing, and checking happens. I have used an_item as a place holder so that I know where I need to figure out the proper value for the function. I have tried all of the pointers I currently have and other values. I even created a temp value(not shown here) but that didn't seem to work either.
void GroceryList::insert(const string& an_item)
{
if (top == an_item.insert)
{
return;
}
char next;
while (!empty())
{
delete(top);
}
if (an_item.insert == NULL)
{
top = NULL;
return;
}
ListNodePtr temp = new ListNode;
temp->item = an_item;
temp->link = top;
top = temp;
}
Here's the rest of GroceryList.cpp
#include <iostream>
#include <cstddef>
#include <string>
#include "GroceryList.h"
using namespace std;
using namespace CS151GroceryList;
GroceryList::GroceryList() : top(NULL)
{
//left blank intentionally
}
GroceryList::~GroceryList()
{
while (!empty())
{
/*remove();*/
delete top;
}
}
bool GroceryList::empty()
{
return(top == NULL);
}
void GroceryList::print()
{
ListNode*temp = top;
while (temp != top)
{
cout << temp->item << endl;
temp = temp->link;
}
cout << temp->item << endl;
}
void GroceryList::remove(const string& an_item)
{
if (empty())
{
cout << "Error: remove was attempted on empty list.\n";
exit(1);
}
}
void GroceryList::insert(const string& an_item)
{
if (top == temp.insert)
{
return;
}
char next;
while (!empty())
{
delete(top);
}
if (an_item.insert == NULL)
{
top = NULL;
return;
}
ListNodePtr temp = new ListNode;
temp->item = an_item;
temp->link = top;
top = temp;
}
bool GroceryList::inList(const string& an_item)
{
ListNodePtr temp;
temp = top;
if (temp == an_item.insert)
{
temp = temp->link;
if (temp != an_item.insert)
{
if (temp->link != temp->link)
{
return 1;
}
}
/*cout << "Item is in list. Failed to insert." << endl;
return 1;*/
}
else
{
cout << "Item is not in list. Inserting." << endl;
return 0;
}
}
This is the error I am getting:
error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::insert': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::insert' to create a pointer to member
I'm pretty sure it is because I am not using the proper value
You have at least these problems in your code:
1)
void GroceryList::insert(const string& an_item)
{
if (top == temp.insert)
{
return;
}
if temp is local variable, then you can't use it without declaration (and, for best, proper initialization). Besides, "insert" is member function call, you've missed the braces and argument list, like that "temp.insert(smth)"
2)
if (an_item.insert == NULL)
{
top = NULL;
return;
}
the same issue, you should provide arguments to member call insert. But you don't need insert call there, because an_item argument of GroceryList::insert, passed by const reference, so you can use it without NULL checks
int listRecSearch(list<int>list, const int data)
{
if (list.empty())
{
cout << "The number is not in the list, try again..." << endl;
return -1;
}
else if (list.back() == data)
{
// cout << "list.size(): " << list.size() << endl;
list.pop_back();//I needed the index begins from 0 instead of 1
return list.size();
}
else
{
// cout << "list.back(): " << list.back() << endl;
list.pop_back();
listRecSearch(list, data);
}
}
//funtion used
int main()
{
list<int>list = listGenerator(size);//generate a list with 20 random numbers.
cout << "Specify the element to be searched for: ";
cin >> data;
int position = listRecSearch(list, data);
if (position > -1)
cout << "\nFind the element at position: " << position << endl;
}
The function listRecSearch was able to display correct list.size() value and correct pop_back values. But once it returned, it always return a garbage value. I figured there were steps were still went through after return, but I can't see where and how.
There exists a code path which does not return a value. listRecSearch(list, data); should become return listRecSearch(list, data);.