I'm attempting to write a C++ program that uses a Point class consisting of x and y coordinates (ints) and a boolean. The x and y coordinates should be in the range from 0-100, but upon execution and with a print statement to test, the values printed out are corrupted.
My code looks like this:
int main(int argc, const char * argv[]) {
vector<Point> points;
for (int i = 0; i<200; i++) {
int rand_X = (rand() % 100) + 1;
int rand_Y = (rand() & 100) + 1;
Point point = Point(rand_X, rand_Y, false);
cout<< point.getX() << " " << point.getY() << endl;
points.push_back(point);
}
return 0;
and the Point class looks like this, if that's relevant:
struct Point {
public:
int x;
int y;
bool in_layer;
Point(int x, int y, bool in_layer) {}
int getX() {return this->x;}
int getY() {return this->y;}
};
And the output is just "-272632592 32766" repeated 200 times, which I'm assuming is a corrupted value.
Any ideas what could be causing the issue?
Your constructor didn't do anything, which contribute to an UB when you call getX getY methods. Plus, I think there's no need to use constructor and getx gety methods here.
If that's a code for learning, you may need to assign to the member x, y in the constructor or use the folowing technique (initialization list):
Point(int _x, int _y, bool _in_layer) : x(_x), y(_y), in_layer(_in_layer){}
Related
I'm a little confused trying to understand what is happening here:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(): x(0), y(0) {}
int getX() {return x;}
int getY() {return y;}
};
int main(int argc, char const *argv[])
{
Point *a = new Point[2];
Point *b = a;
for (int i = 0; i < 5; i++, a++)
cout << a->getX() << "," << a->getY() << endl;
delete[] b;
return 0;
}
Output:
0,0
0,0
0,0
1041,0
825503793,667692
This is just an experiment, I looked at this when I was practicing with classes and dynamic memory.
Why the output look like this, what is happening behind?
I'm sure than the 2 first Point will be initialized with the Point() constructor, so why the third is also 0,0?
And why the other 2 have that random numbers, where are that objects allocated? Are there just random memory / uninitialized memory of Point type?
I'm trying to make a program that will allow the user to enter in a heighth and width of a rectangle, and display the area, however every step of my program is done using functions as part of the assignment.
The issue I'm having is that I have the variables assigned and intialized, though I'm not sure how to overwrite them with user inputted data. If I don't initialize the variables at all the program will not run. I was hoping someone could tell me what I'm doing wrong. My code is:
#include <iostream>
using namespace std;
double getWidth(int x);
double getLength(int y);
double getArea(double x, double y, double a);
double displayData(double a);
int main()
{
int x = 0, y = 0, a = 0;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
There are two ways of passing variables. Method number one is to pass by value. This is the most common method, and it is the one your program is doing. In this method, a copy of the data in the variable is being made and supplied to the function. Your function only changes the copy and not the original variable.
The second method is to pass by reference. When passing by reference, your function effectively has a pointer to the original variable and can thus change it. To pass by reference, put in an ampersand (&) in front of the variable in the function header. Note in the code below that it is not necessary to pass x and y to getArea by reference because getArea only needs to read these variables not write to them.
This however will introduce a new problem for you. When you pass by value it is possible to change the variable type to a larger type without an explicit cast. This is not possible with passing by reference because the different parts of the program would then be trying to treat the variable as a different type. i.e. main wants to write to/read from a as if it is an integer and getArea wants to write to/read from a as if it is a double. These two data types have different sizes and and different formats so this is not possible. Thus you have to declare a is a double in main.
#include <iostream>
using namespace std;
double getWidth(int &x);
double getLength(int &y);
double getArea(double x, double y, double &a);
double displayData(double a);
int main()
{
int x = 0, y = 0;
double a;
getWidth(x);
getLength(y);
getArea(x, y, a);
displayData(a);
system("pause");
return 0;
}
double getWidth(int &x)
{
cout << "Please enter the width: ";
cin >> x;
return x;
}
double getLength(int &y)
{
cout << "Please enter the length: ";
cin >> y;
return y;
}
double getArea(double x, double y, double &a)
{
a = x*y;
return a;
}
double displayData(double a)
{
cout << a << endl;
return a;
}
You seem to be confusing a few different concepts. You should either be passing references and assigning them within the functions, or passing less values and assigning them to some variable in main. For example, your getWidth should be:
double getWidth() {
double w;
cin >> w;
return w;
}
and in your main you should have:
int main() {
/* ... */
double width = getWidth();
/* ... */
}
And so on for the others as well. You should be looking into references and pointers in C++ as well, that would be the other way that you could do this (and you are seemingly confused about). Finally you should definitely find an introduction to functions in some intro to C++ book, as someone said above.
This is a difficult issue but I'm not sure where to turn. To sum it up from the start, I'm having trouble with arrays in c++. To head off your inevitable response, I have to use arrays, I can't use vectors. The reason being that I will eventually be interfacing this with CUDA which can't accept vectors.
Anyway, I have written my own class to handle 2D arrays and all the stuff that goes with that behind the scenes. The header file is reproduced at the bottom of this question. I use this class to define a 6 x 10 array. I then loop over many items, primarily using the add method of my class. At some point in this complicated loop, the size of my array switches from 6 x 10 to 0 x 1074266112. I have tried to debug my code and figure out what the issue is but for the life of me I cannot find the issue.
I've printed out all the values at the moment the array size changes, and none of them are out of the norm and I'm never trying to index the array outside of the 6x10 size. In fact, it never even happens at the same point of the loop, it just seems to happen randomly for each run. The only constant I can find between each issue is that the new array size is always exactly 0 x 1074266112.
Sorry I can't provide a minimum working example, but this issue only crops up in my large program and I can't reproduce it in a smaller program. I was at least hoping anyone could see if I'm doing anything wrong with my Matrix program below and possibly suggest a method of debugging.
EDIT: If I change this to use a vector rather than an array, the issue goes away. I.e., if I change the relevant parts to vector<double> data and upon instantiating, data = *(vector<double>(x * y)), the issue mentioned above is no longer a problem. However I have no idea what could be the problem with making this an array.
#include <vector>
#include <iostream>
#ifndef MATRIX_H
#define MATRIX_H
using std::vector; using std::cout; using std::endl;
class Matrix {
//Define the private variables associated with any instance of this class.
double * data; //The 1D pointer which points to the array
int w, h; //The width and height of the 2D array that the 1D data array represents
public:
Matrix(){}
Matrix(int x, int y){ setSize(x,y); }
void setSize(int x, int y){ w = x; h = y; data = new double[x * y]; setAll(0); }
//Two methods to get the height and width of the effective 2D array
int getWidth(){ return w; }
int getHeight(){ return h; }
//Several methods used to set and get the values of elements within the array as well as extracting
//rows and columns as vectors.
void set(int x, int y, double value){ data[y*w + x] = value; }
void setAll(double value);
double get(int x, int y){ return data[y*w + x]; }
vector<double> getCol(int x);
vector<double> getRow(int y);
//Several methods to adjust the current value by the input
void increment(int x, int y){ data[y*w + w] += 1; }
void add(int x, int y, double value){ data[y*w + x] += value; }
void subtract(int x, int y, double value){ data[y*w + x] -= value; }
void multiply(int x, int y, double value){ data[y*w + x] *= value; }
void divide(int x, int y, double value){ data[y*w + x] /= value; }
};
void Matrix::setAll(double value){
for (int i = 0; i < w*h; i++){
data[i] = value;
}
}
vector<double> Matrix::getCol(int x){
vector<double> column(h);
for (int i = 0; i < h; i++){ column[i] = data[i*w + x]; }
return column;
}
vector<double> Matrix::getRow(int y){
vector<double> row(w);
for (int i = 0; i < w; i++){ row[i] = data[y*w + i]; }
return row;
}
#endif /* MATRIX_H */
Your increment method is wrong; it depends only on y when from context it looks like you intended to also use x in the array index calculation. If you're calling this increment somewhere in your program, you're probably writing to memory off in la-la land somewhere. I don't know if that's the only cause of your issue, but anyway it will corrupt your heap in probably unhelpful ways.
I want to work with Images, and I want to create my structure Image with first 2 values to be it's size (grayscale) and the third - data (2D array of size m by n).
How can I implement it? If I don't know the image's size in advance. Something like this:
struct Image{
int n;
int m;
data = 2D array of size mxn
}
Instead I would use
struct Image{
int n;
int m;
vector<vector<int>> data;
}
Of you could use a 1D vector that has size
vector<int> data(m * n);
Ignoring encapsulation, something like this could work:
#include <vector>
struct Image {
int n;
int m;
std::vector<std::vector<int>> data; // May want to change int type ?
Image(int n, int m) : n(n), m(m), data(n) {
for (int row = 0; row < n; row++) {
data[row].resize(m);
}
}
};
// Example Usage
Image img(10, 10);
for (int row = 0; row < img.n; row++) {
for (int col = 0; col < img.m; col++) {
img.data[row][col] = valueFromImageFile;
}
}
If you're not just looking for something quick and dirty, and this is going to be an ongoing project, I would recommend that you learn more about object oriented concepts :)
There are two common patterns for that (even if inherited from C). Both share a common principle : a logical separation between a fixed size header and a variable part.
First method : the struct contains the fixed size part and a pointer (or pointers in a generic case) to memory allocated with new (in constructor) and deallocated in destructor. It is a bit hand-driven, but easy to use and to understand.
Image could look like (I assume Pixel is a class representing a single pixel):
class Image {
private:
int _x, _y;
Pixel *data;
public:
Image(int x, int y);
~Image();
Pixel& getPixel(int i, int j) {
return data[i * _y + j];
}
};
Image::Image(int x, int y) {
data = new Pixel[x * y];
_x = x;
_y = y;
}
Image::~Image() {
delete[] data;
data = NULL;
}
Second method : the pseudo-struct is composed of a fixed size header, and of a dynamic part. The dynamic part is declared in the struct to be of size 1. It is obviously false, and you cannot use sizeof on such a struct, but as C does not inforce comparison of array to the declared size it works :
class Image {
private:
int _x, _y;
Pixel data[1];
Image(int x, int y); // private to force usage of createImage
public:
static Image* createImage(int x, int y);
Pixel& getPixel(int i, int j) {
return data[i * _y + j];
}
};
Image* Image::createImage(int x, int y) {
Image* image = (Image *) malloc(sizeof(Image) + (x * y - 1) * sizeof(Pixel));
image->_x = x;
image->_y = y;
return image;
}
I must admit it is really C code embedded in C++, but I cited it because it is heavily used in Microsoft Win32 API.
In the .h file given to me by my professor, he's written
double operator()(double x) const;
The point of the overload is to read in x as a double and use it to evaluate a polynomial that's stored in the class object Term. What I've come up with in the class implementation is
double operator()(double x) const
{ double result = 0.0;
for (int i = 0; i < getSize(); i++)
result += (getCoeff(i) * pow(x, getExponent(i)));
return result;
}
How do I call it from the application? I've tried different calls like
Polynomial p;
p.operator(x);
or
Polynomial::operator(x);
or
operator(x);
but always get errors when compiling.
The usual form is to call it as if your instance was a function:
double x = 3.1416;
Polynomial p;
double y = p(x);
Alternatively, you can explicitly call the operator:
double x = 3.1416;
Polynomial p;
double y = p.operator()(x);
Here's a simplified example:
#include <iostream>
struct Foo
{
double operator()(double x) const { return x*2; }
};
int main()
{
Foo f;
std::cout << f(2.5) << std::endl;
}