Pointer, could not print value - c++

may i know why if i'll get something like address from the output.
Can anyone tell me how to make it output as a value?
I'm new to pointer and going to do linked list.
struct node{
int x;
node *next;
};
int main(){
node *root;
root = new node;
root->next = 0;
root->x = 5;
cout << root << endl;
return 0;
}

Well if you really wanted to, you could overload operator<< to output the value of the node class/struct, I'm currently not near a compiler but I assume it would go something as so:
inline std::ostream& operator<< (std::ostream& os, const node* myNode)
{
os << myNode->x;
return os;
}
//Usage:
std::cout << root << std::endl;
Though if you just want to get the value in the simplest way possible, you could always just use
operator-> as shown below:
std::cout << root->x << std::endl;

Same as you assigned value to x
cout << root->x << endl;

you can also access value of x as:
cout<<(*root).x<<endl;

Related

Reference returning blank value

I'm writing a linked list, and using my main function to test it. Here's my code:
#include <iostream>
using namespace std;
class LinkedList {
int value;
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
value = valueIn;
}
int getValue() {
return value;
}
void addNode(LinkedList* node) {
next = node;
}
LinkedList& getNext() {
return *next;
}
};
int main() {
cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;
return 0;
}
I expect the output to be 1 --> 2, but I get 1 -->. As far as I understand, getNext() should return a reference to another list (list2 in this case), but something seems to be going wrong. My debugging efforts show me that list2 does have the correct value 2 when it's initialized, but when it's referenced for the final output, it doesn't seem to have anything for value. I can't for the life of me figure out why this is. Could someone help me to understand?
You are insertin list1(which is actually a node) to the end of list2, not the other way around, yet you call getNext() on list1. You should change the code in main to the below:
int main() {
std::cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
std::cout << list2.getValue() << " --> " << list2.getNext().getValue() << std::endl;
return 0;
}
Please note that there are a couple of other things which would be better to change:
Create a list class and a Node class woud make things clearer
Initializing the pointer to be NULL(or nullptr from C++11) in the LinkedList(int valueIn) constructor
Return the pointer to the node in getNext() rather than copy the node
You are not getting a blank value. Actually your program is crashing when you are trying to call list1.getNext().getValue() as getNext() is returning reference to a NULL.
You are doing the opposite of what you want to do.
Your list2 is pointing to list1 and list1 is pointing to NULL.
You should change your code with this:
LinkedList list2(2);
LinkedList list1(1, &list2);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;

Inserting into the front of a linkedlist

I am having troubles with my code. the calling linkedlist does not seem to get "updated" with the values or they are not saved or something. Could use some help, Thanks.
template <class T>
void LinkedList<T>::insert_front(const T& x)
{
LinkedList* p = this;
LinkedList* tmp = new LinkedList(x,p);
p = tmp;
cout<<p->m_data<<endl;
cout<<tmp->m_data<<endl;
The calling function is
//TEST : Inserting 10 numbers to a
cout << endl << "TEST : Inserting 10 numbers to A" << endl;
for (int k=0; k<10; k++){
A.insert_front(k+1);
}
cout << A << endl;
cout << "Size of a = " << A.size() << endl;
I get an output of 1122334455667788991010
which is the tmp data value and the p data value each call
The values go to the code, and they are the right values, just when I go to print A nothing is shown just an empty list. Thanks, I'm new here but love the community.
Your design of the linked list and of the method are wrong.
In the method you defined local variable p and assigned to it tmp. After exiting the method this local variable will be destroyed. So nothing was occured with the list itself. Neither its data member was changed. Also there is a memory leak.
template <class T>
void LinkedList<T>::insert_front(const T& x)
{
LinkedList* p = this;
LinkedList* tmp = new LinkedList(x,p);
p = tmp;
cout<<p->m_data<<endl;
cout<<tmp->m_data<<endl;
You should split you class into two classes. The first one will define the node of the list and the second one will control operations withy the list and contain the head of the list as its data member.

Iterator for structure "node" is not allowing data retrieval

I'm struggling with an issue. I have our regular node structure and a list that stores node pointers. When I'm trying to retrieve values fro such list using an iterator, I'm not able to do so...
#include <list>
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
int main()
{
node * n = new node;
n->data = 3;
n->next = NULL;
list<node*> l;
l.push_front(n);
list<node*>::iterator myIt = l.begin();
cout << *myIt->data << endl; // <-- the compiler shows an error here "Member reference base type "node*" is not a structure or union"
}
Perhaps I'm confused with the usage of iterators. Could you please suggest me a workaround?
Cheers!!!
Problem with operators precedence: use cout << (*myIt)->data << endl;
cout << *myIt->data << endl;
You need additionnal ()
cout << (*myIt)->data << endl;
Bye,
Francis
You are actually a bit confused, you need to do the following
cout << (*myIt)->data << endl;
You first have you dereference the pointer, then you can fetch the data.

c++ overload pointer ostream

I am a learning c++ and have a class project due in 5 days. I've spent 4 hours researching how to do this however I have not come up with an answer yet. Save me stack!
Problem. I have a pointer to a class which holds a dynamic array. I need to take that array and save it to a file to retrieve later. Here are my 2 headers and the implementation. I am not writing the code to "save to file" yet as that will be easy once I get around this issue. My problem is it keeps printing the address of the pointer and not the data within.
vehReg.h
class vehReg {
public:
/* STUFF */
};
}
#endif
vehData.h
#include "vehReg.h"
using namespace std;
class vehData {
public:
//CONSTRUCTORS
vehData();
//DECONSTRUCTOR
~vehData();
//METHODS
friend ostream &operator<<( ostream &output, const vehData &v);
private:
typedef unsigned long longType;
typedef std::size_t sizeType;
sizeType used,capacity;
vehReg *data;
};
}
#endif
vehData.cpp
//CONSTRUCTOR
vehData::vehData(){
capacity = 5;
used = 0;
data = new vehReg[capacity];
}
//DECONSTRUCTOR
vehData::~vehData(){
delete []data;
}
/* TRYING TO ACCOMPLISH THIS WITH AN OSTREAM OVERLOAD */
void vehData::saveDataSloppy(){
ofstream myFile;
myFile.open ("database.db");
for(int i=0;i<used;i++){
myFile << data[i].getOwnerName() << "|";
myFile << data[i].getVehicleLicense() << "|";
myFile << data[i].getVehicleMake() << "|";
myFile << data[i].getVehicleModel() << "|";
myFile << data[i].getVehicleYear() << "\n";
}
myFile.close();
}
void vehData::saveData(){
cout << data;
}
ostream &operator<<(ostream &stream, const vehData &v){
stream << v.data;
}
}
v.data is a pointer, so it prints a pointer. How do you want it to
print whatever the pointer points to. With the exception of character
pointers, the << always prints what you give it (formatted in some
way). If you don't want it to print a pointer, give is something else.
Suppose it did dereference the pointer. What should it print: one
vehReg? 20? A pointer has no information concerning the size. If
you'd used std::vector<vehReg> (a much better choice), it would know
the size, but there's still no overload on std::vector, since the
system still doesn't know how you want it formatted (comma separated?
each on a new line?). And you've not told it how to print a vehReg
either.
You apparently understand the idea of how to overload <<. The first
thing you'll have to do is provide an overload for vehReg as well.
And both overloads must be defined in terms of existing overloads:
there's not one for std::vector, and the one for pointer doesn't do
what you want (and couldn't), so you'll have to loop in your << for
vehData and output each element, with whatever separators you decide
on. (If it's each element on its own line, then you can use std::copy
and an ostream_iterator for the loop, but this may be a bit in advance
of what you've learnt so far.) And forward to the << for vehReg for
each vehReg.
v.data is a pointer so it's a memory address.
*v.data is what the pointer is pointing to (which in this case is an integer).
For example,
#include <iostream>
using namespace std;
void main () {
int *ptr;
int var = 5;
ptr = &var;
cout << ptr << endl;
cout << *ptr << endl;
system("pause");
}
First line will print out something like: 0043F930
Second line will print out: 5
This should print out the elements held in the data array.
void vehData::showStructure() const {
for (int i = 0; i < capacity: i++) {
cout << data[i];
}
cout << endl;
}

Can't get constructor to run

I'm trying to create a doubly linked list where each list has a first node, last node, and num_elements. However, for some reason, when I try to test the code in a UseList.cpp file, I can't get the num_elements to set to zero as default.
Let me show you what I mean:
In List.h:
template <class L>
class List
{
private:
Node<L> *first;
Node<L> *last;
int num_elements;
public:
// constructors and destructors
List();
[...]
}
[...]
template <class L>
List<L>::List() {
first = NULL;
last = NULL;
num_elements = 0;
}
[...]
This is the show method lower down in list.h:
template <class L>
// Print out the data in each node separated by a space.
void List<L>::show() {
cout << num_elements << endl;
Node<L> *current_node = first;
while (current_node != NULL) {
cout << current_node->data << " ";
current_node = current_node->next;
}
cout << endl;
}
Note that there is a cout statement there to print the num_elements.
This is the relevant part of UseList.cpp:
int main (int argc, char *argv[]) {
cout << "-----------------------------------------" << endl;
cout << "----------------LIST ONE-----------------" << endl;
cout << "-----------------------------------------" << endl;
List<int> *list1;
srand(time(NULL));
list1->show();
[...]
When show is called, it prints out "1" and gives me a segmentation fault. Why is num_elements defaulting to "1" instead of "0"?
When I do a cout in List<L>::List() {, nothing is printed... (this implies that the constructor never runs?)
Thanks for the help!
You are declaring a pointer to a List<int> and not initializing it to anything.
You have created a pointer to a List<int> object, but no object. So, currently, your program will segmentation fault because the pointer is "dangling". When you try to dereference it with ->, you are accessing memory that isn't yours, and it fails. To fix this, simply allocate a new List object:
List<int> *list1 = new List<int>();
Don't forget to free it later:
delete list1;
Your other option is to just not use dynamic memory. You shouldn't use it if you don't have to.
List<int> list1;
list1.show()
List<int> *list1;
Declares list1 to be a pointer.
List<int> *list1 = new List<int>();
Would actually create an instance of List