Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm getting these results:
constructor
setFunc
setFunc
Basically I want my class-object globally and pass the struct array to setMethod of the class. and Program is successfully compiling but not getting any results.
DataInput.h
#ifndef DATAINPUT_H_
#define DATAINPUT_H_
#include <stdio.h>
struct Data{
const char *name;
int salary;
void set(int salary, const char *name){
printf("setFunc \n");
this->name = name;
this->salary = salary;
}
};
This class in a seprate cpp file with above header file
class DataInput {
public:
int dataSize;
struct Data data[];
DataInput();
virtual ~DataInput();
void setData(struct Data d[], int numberOfData);
void printData();
private:
};
#endif
-------eof----------
DataInput.cpp
#include "DataInput.h"
DataInput::DataInput() {
printf("constructor \n");
dataSize = 0;
}
DataInput::~DataInput() {
}
void DataInput :: setData(struct Data d[], int numberOfData){
dataSize = numberOfData;
for (int i = 0; i< numberOfData; i++){
printf("i-val in setData() --> %d",i);
this->data[i] = data[i];
}
}
void DataInput::printData(){
for (int i = 0; i< dataSize; i++){
printf("name--> %s \n",data[i].name);
printf("salary--> %d \n",data[i].salary);
}
}
--------eof-----------
main.cpp
#include <stdlib.h>
#include "DataInput.h"
#include <stdio.h>
DataInput *dataInput;
int main(void) {
DataInput in;
dataInput = ∈
struct Data d[2];
d[0].set(1000, "ABC");
d[1].set(2000, "XYZ");
dataInput->setData(d, 2); //not setting data
dataInput->printData(); //not printing
return 0;
}
Note: May not compile, is just illustrative
Few things:
DataInputconstructor do not reserve space for new items. So, this->data[i] = data[i]; result is undefined.
This is C++, Rule of three, strings, ....
struct Data
{
std::string name;
int salary;
Data(const std::string & n, int s);
Data & operator=(const Data & d);
};
Data::Data(const std::string & n, int s) :
name(n), salary(s)
{
}
Data & Data::operator=(const Data & d)
{
name = d.name;
salary = d.salary;
return *this;
}
Use standards containers:
class DataInput
{
private:
std::vector<Data> data;
public:
DataInput();
virtual ~DataInput();
// you don't need use size
void setData(const std::vector<Data> & d);
void printData();
};
void DataInput::setData(const std::vector<Data> & d)
{
data = d;
}
void DataInput::printData()
{
for (std::vector<Data>::iterator it = data.begin(); it != data.end(); ++it)
{
std::cout << it->name << ":" << it->salary << std::endl;
}
}
Now, you can use it from main (without pointers):
int main(void)
{
DataInput in;
std::vector<Data> d;
d.push_back(Data(1000, "ABC"));
d.push_back(Data(2000, "XYZ"));
dataInput.setData(d); // yes setting data
dataInput.printData(); // yes printing
return 0;
}
Do a memcpy of the entire array, just assigning the data might lead to memory leaks due to stack frame removal or deletion. This way however you lose the logging simultaneously avoiding the for loop increasing performance
void DataInput :: setData(const struct Data const* d, const int numberOfData) {
// Cleanup old data!
if(this->data) delete [] this->data;
if(!d) throw new std::invalid_argument("Cannot set NULL data!"); // Remove this line if NULL may be assigned and replace with the commented code.
// if(!d) {
// this->data = NULL;
// this->dataSize = 0;
// } else {
this->data = new Data[(this->dataSize = numberOfData)];
memcpy(this->data, d, sizeof(struct Data) * numberOfData);
// }
}
Don't forget to update the DataInput class!
class DataInput {
public:
int dataSize;
struct Data* data;
DataInput();
virtual ~DataInput();
void setData(const struct Data const* d, const int numberOfData);
void printData();
private:
};
void DataInput::printData() {
for (int i = 0; i< this->dataSize; i++){
printf("name--> %s \n",this->data[i].name);
printf("salary--> %d \n",this->data[i].salary);
}
}
DataInput::~DataInput() {
if(this->data) delete [] this->data;
}
Related
I'm pretty new to C++ and am trying to teach myself how to implement a hash table(I know I could use unordered_map, but I'm challenging myself). Right now I have a vector of structs(cell) that holds person-specific information. I have a PrintTable function that I want to use to print out each struct member of every item in the table. However, I can't seem to access the specific members of the struct(cell). What am I doing wrong here?
#include <iostream>
#include <string>
#include <vector>
struct cell
{
std::string name;
int age;
std::string weapon;
};
class HashTable
{
private:
std::vector<cell> *table;
int total_elements;
int getHash(int key)
{
return key % total_elements;
}
public:
HashTable(int n)
{
total_elements = n;
table = new std::vector<cell>[total_elements];
}
void SearchTheTable(int hashIndex);
void AddItem(std::string name, int age, std::string weapon);
void RemoveItem();
void PrintTable();
};
void HashTable::SearchTheTable(int hashIndex)
{
int x = getHash(hashIndex);
std::cout << x;
}
void HashTable::AddItem(std::string name, int age, std::string weapon)
{
cell newCell = { name, age, weapon };
table->push_back(newCell);
}
void HashTable::RemoveItem()
{
}
void HashTable::PrintTable()
{
for (int i = 0; i < table->size; i++)
{
std::cout << table[i].name; // Right here I get an error that says: class "std::vector<cell, std::allocator<cell>>" has no member "name".
}
}
int main()
{
HashTable theTable(5);
theTable.AddItem("Ryan", 27, "Sword");
theTable.AddItem("Melony", 24, "Axe");
theTable.PrintTable();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i am new to c++ and i am currently trying to write a program that uses main to call functions which are seperately written and i tried to write the definitions for the header file declarations and i am getting errors with some functions which i have marked in the code
Store.hpp
#ifndef STORE_HPP
#define STORE_HPP
class Product;
class Customer;
#include<string>
#include "Customer.hpp"
#include "Product.hpp"
class Store
{
private:
std::vector<Product*> inventory;
std::vector<Customer*> members;
public:
void addProduct(Product* p);
void addMember(Customer* c);
Product* getProductFromID(std::string);
Customer* getMemberFromID(std::string);
void productSearch(std::string str);
void addProductToMemberCart(std::string pID, std::string mID);
void checkOutMember(std::string mID);
};
#endif
i am having trouble writing the code for that function help me
store.cpp
#include <iostream>
#include <string.h>
#include "Customer.hpp"
#include "Store.hpp"
#include "Product.hpp"
using namespace std;
string id;
void Store::addProduct(Product* p) //error 1 no matching function
{
Product* p(std::string id, std::string t, std::string d, double p, int qa);
inventory.push_back(p);
}
void Store:: addMember(Customer* c)
{
members.push_back(c->getAccountID());
}
Product* Store::getProductFromID(std::string id)
{
for(int i = 0; i < inventory.size(); i++)
{
Product* p=inventory.at(i);
if(p->getIdCode()= id)
{
return p;
}
}
return NULL;
}
Customer* Store:: getMemberFromID(std::string id)
{
for(int i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if(c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
void std::Store productSearch(std::string str)
{
for(int i = 0; i < inventory.size(); i++)
{
if(inventory[i] == str)
{
Product stud(inventory[i],inventory[i+1],inventory[i+2],inventory[i+3],inventory[i+4]);
cout<<getIdCode();
cout<<getTitle();
cout<<getDescription();
cout<<getPrice();
cout<<getQuantityAvailable();
}
}
}
void addProductToMemberCart(std::string pID, std::string mID)
{
cout<<"adding to cart"<<endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void checkOutMember(std::string mID)
{
Customer* c=getAccountID(mID)
mID=getMemberFromID(std::string mID);
if(mID=="NULL")
{
cout<<mID<<"is not found"<<endl;
}
}
customer.hpp
#ifndef CUSTOMER_HPP
#define CUSTOMER_HPP
#include<vector>
#include "Product.hpp"
class Customer
{
private:
std::vector<std::string> cart;
std::string name;
std::string accountID;
bool premiumMember;
public:
Customer(std::string n, std::string a, bool pm);
std::string getAccountID();
//std::vector getCart();
void addProductToCart(std::string);
bool isPremiumMember();
void emptyCart();
};
#endif
product.hpp
#ifndef PRODUCT_HPP
#define PRODUCT_HPP
#include<vector>
class Product
{
private:
std::string idCode;
std::string title;
std::string description;
double price;
int quantityAvailable;
public:
Product(std::string id, std::string t, std::string d, double p, int qa);
std::string getIdCode();
std::string getTitle();
std::string getDescription();
double getPrice();
int getQuantityAvailable();
void decreaseQuantity();
};
#endif
You code issues lots of warnings and errors as stands.
If you find yourself in this situation and can't figure out what one of them means, try to fix some of the others.
Your main problem is in addProduct, but there are others
using namespace std;
string id; //<---- what's this for?
void Store::addProduct(Product* p) //error 1 no matching function
{
//Product* p(std::string id, std::string t, std::string d, double p, int qa);
//<--- This line had the error and isn't needed
inventory.push_back(p);
}
void Store::addMember(Customer* c)
{
// members.push_back(c->getAccountID()); //<--- this errors too
members.push_back(c);
}
Product* Store::getProductFromID(std::string id)
{
for (size_t i = 0; i < inventory.size(); i++)
{
Product* p = inventory.at(i);
//if (p->getIdCode() = id) //<-- be careful with = and ==
if (p->getIdCode() == id) //<---
{
return p;
}
}
return NULL;
}
Customer* Store::getMemberFromID(std::string id)
{
for (size_t i = 0; i < members.size(); i++)
{
Customer* c = members.at(i);
if (c->getAccountID() == id)
{
return c;
}
}
return NULL;
}
//void std::Store productSearch(std::string str)
void Store::productSearch(std::string str) // <---- note this change too
{
for (size_t i = 0; i < inventory.size(); i++)
{
//if (inventory[i] == str) //<<--------!
if (inventory[i]->getDescription() == str)
{
//Product stud(inventory[i], inventory[i + 1], inventory[i + 2], inventory[i + 3], inventory[i + 4]);
// This is five Products from the inventory, not the i-th product in your invetory
Product stud(*inventory[i]);//<---- I assume
cout << stud.getIdCode();
cout << stud.getTitle();
cout << stud.getDescription();
cout << stud.getPrice();
cout << stud.getQuantityAvailable();
}
}
}
void Store::addProductToMemberCart(std::string pID, std::string mID)//<--- note note std::Store addProductToMemberCart
{
cout << "adding to cart" << endl;
getMemberFromID(mID)->addProductToCart(pID);
}
void Store::checkOutMember(std::string mID)//<---
{
//Customer* c = getAccountID(mID);//<<---?
//mID = getMemberFromID(std::string mID); //<---?
Customer* c = getMemberFromID(mID); //Just this?
if (c == NULL)//<---rather than "NULL" but nullptr might be better
{ // or not using pointers at all
cout << mID << "is not found" << endl;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a application that is suppose to store graphic elements. I am having an issue where I cant access a variable in a structure. Here is what i have so far.
#include <crtdbg.h>
#include <string.h>
#include <stdio.h>
#include "CLib.h"
enum{ RUNNING = 1 };
struct Point
{
int x, y;
};
struct Line
{
Point start;
Point end;
};
struct GraphicElement
{
enum{ SIZE = 256 };
char name[SIZE];
CStash Lines; // a Stash of Lines
};
struct VectorGraphic
{
CStash Elements; // a Stash of GraphicElements
};
void AddGraphicElement(VectorGraphic*);
void ReportVectorGraphic(VectorGraphic*);
void CleanUpVectorGraphic(VectorGraphic*);
VectorGraphic Image;
int main()
{
char response;
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// it's a Stash of GraphicElements initialize(&(Image.Elements),sizeof(GraphicElement));
while (RUNNING)
{
printf("\nPlease select an option:\n");
printf("1. Add a Graphic Element\n");
printf("2. List the Graphic Elements\n");
printf("q. Quit\n");
printf("CHOICE: ");
fflush(stdin);
scanf("%c", &response);
switch (response)
{
case '1':AddGraphicElement(&Image); break;
case '2':ReportVectorGraphic(&Image); break;
case 'q':CleanUpVectorGraphic(&Image); return 0;
default:printf("Please enter a valid option\n");
}
printf("\n");
}
return 0;
}
void AddGraphicElement(VectorGraphic* pImage){
int i = 0, counter = 0;
int xPointStart = 0, yPointStart = 0;
int xPointEnd = 0, yPointEnd = 0;
char name[50];
int lineNumber = 0;
GraphicElement *pElement = nullptr;
Line *pLine = nullptr;
initialize(&(Image.Elements), sizeof(GraphicElement));
printf("ADDING A Graphic Element\n");
printf("Please enter the name of the new GraphicElement(<256 characters): ");
fflush(stdin);
scanf("\n%[^\n]s", &name);
fflush(stdin);
strcpy(pElement->name,name);
Anytime I try assigning strcpy(pElement->name,name); it tells me access violation.
The two other files im working with that cannot be changed and are from a textbook called Thinking in C++.
//: C04:CLib.cpp {O}
// Implementation of example C-like library
// Declare structure and functions:
#include "CLib.h"
#include <iostream>
#include <cassert>
using namespace std;
// Quantity of elements to add
// when increasing storage:
const int increment = 100;
void initialize(CStash* s, int sz)
{
s->size = sz;
s->quantity = 0;
s->storage = nullptr;
s->next = 0;
}
int add(CStash* s, const void* element)
{
if (s->next >= s->quantity) //Enough space left?
inflate(s, increment);
// Copy element into storage,
// starting at next empty space:
int startBytes = s->next * s->size;
unsigned char* e = (unsigned char*)element;
for (int i = 0; i < s->size; i++)
s->storage[startBytes + i] = e[i];
s->next++;
return(s->next - 1); // Index number
}
void* fetch(CStash* s, int index)
{
// Check index boundaries:
assert(0 <= index);
if (index >= s->next)
return 0; // To indicate the end
// Produce pointer to desired element:
return &(s->storage[index * s->size]);
}
int count(CStash* s)
{
return s->next; // Elements in CStash
}
void inflate(CStash* s, int increase)
{
assert(increase > 0);
int newQuantity = s->quantity + increase;
int newBytes = newQuantity * s->size;
int oldBytes = s->quantity * s->size;
unsigned char* b = new unsigned char[newBytes];
for (int i = 0; i < oldBytes; i++)
b[i] = s->storage[i]; // Copy old to new
delete[](s->storage); // Old storage
s->storage = b; // Point to new memory
s->quantity = newQuantity;
}
void cleanup(CStash* s)
{
if (s->storage != 0)
{
cout << "freeing storage" << endl;
delete[]s->storage;
}
} ///:~
and the .h file...
//: C04:CLib.h
// Header file for a C-like library
// An array-like entity created at runtime
typedef struct CStashTag {
int size; // Size of each space
int quantity; // Number of storage spaces
int next; // Next empty space
unsigned char* storage;// Dynamically allocated array of bytes
} CStash;
void initialize(CStash* s, int size);
void cleanup(CStash* s);
int add(CStash* s, const void* element);
void* fetch(CStash* s, int index);
int count(CStash* s);
void inflate(CStash* s, int increase);
///:~
GraphicElement *pElement = nullptr;
// ...
strcpy(pElement->name,name);
Somewhere between the top line and bottom line above you need to allocate memory for pElement.
pElement = new GraphicElement();
Also, consider using a std::shared_ptr instead of a raw pointer, given you tagged this C++.
I'm using an example code given to me by another C++ coder for a project. I'm a new student of C++ language and I wondered is there a possible memory leak / bugs in this class file given to me (PlacementHead.cpp):
#include "PlacementHead.h"
#include <string>
#include <iostream>
#include <string.h>
PlacementHead::PlacementHead(int width, int height, int gap, char* s) {
width_ = width;
height_ = height;
gap_ = gap;
size_ = (width*height)+1;
set_ = new char[size_ + 1];
from_ = new int[size_ + 1];
original_ = new char[size_ + 1];
strcpy(set_,s);
strcpy(original_,s);
}
PlacementHead::~PlacementHead() {
}
int PlacementHead::getSize() { return size_; }
int PlacementHead::getHeight() { return height_; }
int PlacementHead::getWidth() { return width_; }
int PlacementHead::getGap() { return gap_; }
// Palauttaa indeksissä i olevan suuttimen
char PlacementHead::getNozzle(int i) {
return set_[i-1];
}
// Asettaa indeksissä i olevan suuttimen
void PlacementHead::setNozzle(int i, char c) {
set_[i-1] = c;
}
// Merkitsee suuttimen poimituksi poistamalla sen listasta
void PlacementHead::markNozzle(int i, int bankPos) {
set_[i-1] = ' ';
from_[i-1] = bankPos;
}
// Palauttaa seuraavan poimimattoman suuttimen indeksin
int PlacementHead::getNextUnmarkedPos() {
for (int i=0; i<size_; i++) {
if (set_[i]!=' ') {
return i+1;
}
}
return 0;
}
// Palauttaa suuttimen alkuperäisen sijainnin pankissa
int PlacementHead::getBankPos(int i) {
return from_[i-1];
}
// Plauttaa alkuperäisen ladontapaan suutinjärjestyksen
void PlacementHead::reset() {
//for (int i=0; i<size_; i++) {
// set_[i] = original_[i];
//}
strcpy(set_,original_);
}
// Tulostusmetodi
void PlacementHead::print() {
std::cout << "ladontapaa:\n";
for (int h=height_; h>0; h--) {
for (int w=width_; w>0; w--) {
int i = ((h-1)*width_)+w;
std::cout << getNozzle(i);
}
std::cout << "\n";
}
}
PlacementHead.h:
#ifndef PLACEMENTHEAD_H
#define PLACEMENTHEAD_H
class PlacementHead {
public:
PlacementHead(int size, int rows, int gap, char* s);
~PlacementHead();
int getSize();
int getHeight();
int getWidth();
int getGap();
char getNozzle(int i);
void setNozzle(int i, char c);
void markNozzle(int i, int bankPos);
int getNextUnmarkedPos();
int getBankPos(int i);
void reset();
void print();
private:
char* set_;
int* from_;
char* original_;
int size_;
int width_;
int height_;
int gap_;
};
#endif
I notice that there is dynamic allocation of memory, but I don't see a delete anywhere...is this a problem? How could I fix this if it is a problem?
Thnx for any help!
P.S.
I noticed there is no keyword class used in this example?...Can you define a class like this?
It's impossible to say without seeing the class definition (the
header); if size_, etc. are something like
boost::shared_array, or std::unique_ptr, there is no leak.
If they are simply int*, there is a leak.
Of course, no C++ programmer would write this sort of code
anyway. The class would contain std::vector<int> and
std::string. Judging from what we see here, the author
doesn't know C++.
the code has leak . the constructor allocates the memory .Destructor or some other function have to clean that before the object gets destroyed
Another problem is that your code does not obey Rule of three (links here and here)
once you will write code like:
{
PlacementHead a(0,0,0,"asdsa");
PlacementHead b(0,0,0,"asdsa");
a = b; // line 1
} // here segfault
you will get segfault, in line 1, pointers will be copied from b to a, and once you will finally have destructors, pointers will be deleted twice, which is wrong. This is called shallow copy, you need deep copy, where new array will be allocated.
Hey i'm new to c++ and still working out its perticularities. I'm having the darnedest time trying to figure out whats going wrong with this code. I've stepped through it and everything is calculating correctly. The issue is that value_array in the base class doesn't seem to be retaining the values once the derived class Calculate function ends. I think i've declared and allocated the array properly. I'm stumped...
#include <iostream>
class Indicator
{
protected:
double * value_array;
double * input_array;
int input_size;
public:
Indicator(double input[], int size)
{
input_array = input;
input_size = size;
value_array = new double[size]; // issue with value_array
}
double operator[] (int index) { return value_array[index]; }
void virtual Calculate() {}
~Indicator() { delete[] value_array; }
};
class SMA : public Indicator
{
private:
int nperiod;
double sum;
public:
SMA(double input[], int size, int period) : Indicator(input, size)
{
nperiod = period;
sum = 0;
Calculate();
}
void Calculate();
};
void SMA::Calculate()
{
for (int i=0; i<input_size; i++)
{
if (i > nperiod - 1)
{
sum += input_array[i] - input_array[i-nperiod];
value_array[i] = sum / nperiod;
}
else
{
sum += input_array[i];
value_array[i] = sum / (i+1);
}
}
}
int main(int argc, const char *argv[]) {
double input[] = {1,2,3,4,5,6,7,8,9,10};
Indicator indicator = SMA(input,10,5);
double value = indicator[0];
std::cout << "value: " << value << std::endl;
std::cin.get();
exit(0);
}
Update:
Here is the code implemented with vectors. I wanted to leave the input as double[] to be consistent with other libraries, any other potential issues I should be aware of?
#include <iostream>
#include <vector>
class Indicator
{
protected:
std::vector<double> value_vector;
double * input_array;
int input_size;
public:
Indicator(double input[], int size)
{
input_array = input;
input_size = size;
value_vector.reserve(size);
}
double operator[] (int index) { return value_vector[index]; }
void virtual Calculate() {}
};
class SMA : public Indicator
{
private:
int nperiod;
double sum;
public:
SMA(double input[], int size, int period) : Indicator(input, size)
{
nperiod = period;
sum = 0;
Calculate();
}
void Calculate();
};
void SMA::Calculate()
{
for (int i=0; i<input_size; i++)
{
if (i > nperiod - 1)
{
sum += input_array[i] - input_array[i-nperiod];
value_vector.push_back(sum / nperiod);
}
else
{
sum += input_array[i];
value_vector.push_back(sum / (i+1));
}
std::cout << "sma: " << value_vector[i] << std::endl;
}
}
int main(int argc, const char *argv[]) {
double input[] = {1,2,3,4,5,6,7,8,9,10};
Indicator indicator = SMA(input,10,5);
for (int i=0; i<10; i++)
{
std::cout << "main: " << indicator[i] << std::endl;
}
std::cin.get();
exit(0);
}
That's because you're violating the Rule of Three. Since your class manages a resource, it needs a copy constructor and an assignment operator. I strongly suggest replacing any T* data member with a std::vector<T> data member. Then you don't need to write those special member functions manually.
Hia,
a few things are wrong.
As FredOverflow says you need a copy constructor and assignment, something like:
Indicator::Indicator(const Indicator& other)
{
input_size = other.input_size;
//direct copy of reference as indicator doesn't own this data
//Note a shared pointer (such as boost::shared_ptr) would be better than a naked reference
input_array = other.input_array;
//construct a new set of data
value_array = new double[input_size];
//do you want to copy the data too? maybe a memcpy follows?
memcpy(value_array, other.value_array, input_size*sizeof(double));
}
Then you need an assignment
Indicator&
Indicator::operator=(const Indicator& other)
{
//make sure you are not assigning itself
if(this != &other)
{
input_size = other.input_size;
//direct copy of reference as indicator doesn't own this data
//Note a shared pointer (such as boost::shared_ptr) would be better than a naked reference
input_array = other.input_array;
//destroy old data and construct a new set of data
delete[] value_array;
value_array = new double[input_size];
//do you want to copy the data too? maybe a memcpy follows?
memcpy(value_array, other.value_array, input_size*sizeof(double));
}
return *this;
}
You probably also want to make the destructor virtual - see here for why -
it helps prevent memory leaks in the destructor of SMA
virtual ~Indicator() { delete[] value_array; }
Use std::vector instead of raw arrays.
std::vector handles all the memory management and copying and so forth.
Cheers & hth.,