I am trying to switch the elements of a class array using pointers. It is not outputting what I want. I tried using pointers in the function, but it's not allowed. It's also not allowed to call the function onto the class object without using a pointer, since I declared the class object using a double pointer. I am not using this method simply to solve a small problem, but just to practice using this method for more difficult problems.
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
class thing{
public:
int index;
int value;
thing();
private: int number;
};
thing::thing()
{
number = 0;
}
void arrange(thing array[]){
for(int i=0; i<19; ++i){
if(array[i].value<array[i+1].value){
swap(array[i], array[i+1]);
arrange(array);
}
}
}
int main(){
thing** things = new thing*[20];
for (int i=0; i < 20; ++i)
{
things[i] = new thing(); // default constructor
things[i]->index = i;
things[i]->value=rand() % 100;
}
cout << "The random array is: " << endl;
for(int i=0;i<20;++i){
cout << things[i]->value << endl;
}
arrange(*things);
cout << "The arranged array is: " << endl;
for (int i=0; i < 20; ++i)
{
cout << things[i]->value << endl;
}
return 0;
}
When you call arrange(*things), you're just passing the first element of things to the function, not the array. It should be array(things). Then the arrange function should be written to use pointers:
void arrange(thing* array[]){
for(int i=0; i<19; ++i){
if(array[i]->value<array[i+1]->value){
swap(array[i], array[i+1]);
arrange(array);
}
}
}
Here you create an array of pointers to thing:
thing** things = new thing*[20];
Here you dereference it and get a pointer to thing which is stored at thing[0]:
arrange(*things);
But this function declaration
void arrange(thing array[])
treats this pointer as an array of thing, so that *things points to it first element, which is absolutely not what it really is.
You should change your arrange() function to use correct type:
void arrange(thing* array[]){
for(int i=0; i<19; ++i){
if(array[i]->value<array[i+1]->value){
swap(array[i], array[i+1]);
arrange(array);
}
}
}
And call it as:
arrange(things);
Regarding using vectors, you don't need to use any pointers at all.
std::vector<thing> things(20);
for (int i=0; i < things.size(); ++i)
{
things[i].index = i;
things[i].value=rand() % 100;
}
arrange(things);
void arrange(std::vector<thing>& array){
for(int i=0; i + 1 < things.size(); ++i){
if(array[i].value<array[i+1].value){
swap(array[i], array[i+1]);
arrange(array);
}
}
}
Related
Very new beginner here and I'm at the end of my rope with this assignment and would really appreciate any help :). Apologies in advance for the length.
I'm having some trouble with retrieving and setting values for my dynamically allocated 2D array. I have a class, defined below, that should construct a 2D array, at which point I need the option to set a value to a given point in the array and also to retrieve a value at a given point.
I ran the debugger, and got as far as to figure out that I have a segmentation fault when the setValue function runs. Can anyone help me understand what I'm doing wrong? As a beginner, the easier terms the better :). Thank you kindly in advance.
#include <iostream>
using namespace std;
class array2D
{
protected:
int xRes;
int yRes;
float ** xtable;
public:
array2D (int xResolution, int yResolution);
~array2D() {}
void getSize(int &xResolution, int &yResolution);
void setValue(int x,int y,float val);
float getValue(int x,int y);
};
array2D::array2D(int xResolution, int yResolution)
{
xRes=xResolution;
yRes=yResolution;
float ** xtable = new float*[yResolution];
for(int i=0;i < yResolution;i++)
{
xtable[i] = new float[xResolution];
}
for(int i=0;i < yRes;i++)
{
for(int j=0;j < xRes;j++)
{
xtable[i][j]=45;
}
}
}
void array2D::getSize(int &xResolution, int &yResolution)
{
xResolution=xRes;
yResolution=yRes;
cout << "Size of Array: " << xResolution << ", " << yResolution << endl;
}
void array2D::setValue(int x,int y,float val)
{
xtable[x][y] = val;
}
float array2D::getValue(int x,int y)
{
return xtable[x][y];
}
int main()
{
array2D *a = new array2D(320,240);
int xRes, yRes;
a->getSize(xRes,yRes);
for(int i=0;i < yRes;i++)
{
for(int j=0;j < xRes;j++)
{
a->setValue(i,j,100.0);
}
}
for(int i=0;i < yRes;i++)
{
for(int j=0;j < xRes;j++)
{
cout << a->getValue(i,j) << " ";
}
cout << endl;
}
delete[] a;
}
The line
float ** xtable = new float*[yResolution];
creates a function local variable. The member variable of the class still remains uninitialized. That's not what you want. To allocate memory and assign it to the member variable, remove the type specifier from that line. Just use:
xtable = new float*[yResolution];
Also, you need to switch the use of yResolution and xResolution in those lines. Otherwise, getValue and setValue will be using the indices incorrectly.
Swap the use of xResolution and yResolution in the following lines so that you use:
float ** xtable = new float*[xResolution];
for(int i=0;i < xResolution;i++)
{
xtable[i] = new float[yResolution];
}
Swap the use of xRes and yRes in the following lines so that you use:
for(int i=0;i < xRes;i++)
{
for(int j=0;j < yRes;j++)
{
xtable[i][j]=45;
}
}
Since your class acquires resources using dynamic memory allocation, you should read up on The Rule of Three and update your class accordingly.
int r,c;
cin>>r>>c;
int** p=new int*[r];
for(int i=0;i<r;i++) {
p[i]=new int[c];
}
for(int i=0;i<r;i++) {
delete [] p[i];
}
delete [] p;
Using this code you can create a 2D Dynamic Array in C++ which would allocate the memory of this array in the Heap Memory.
I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;
I am trying to understand passing by reference and passing by value. In this program I have a two dimensional array which is declared in main and whose size is allocated in a function. In the allocate2DArrayRef() function, I obtain the two sizes and dynamically allocate and initialize the array Array2D.
Now I am trying to understand how to do the same by pointers. I have written another function allocate2DArrayPtr() in where I pass a pointer to the two dimensional array, get the value of the sizes - sizeX and sizeY and then allocate the memory to the variable secArray2D.
When I run the program it hangs when I try to print out secArray2D. I am assuming this implies that the function allocate2DArrayPtr() has not been successful in dynamically allocating memory to the array secArray2D.
My final goal is to write a program which has a function that dynamically allocated memory and initializes multiple arrays of various dimensions which are read from an input file. I know I can expand on passing by reference function allocate2DArrayRef() to achieve my goal. But I am curious to learn why my function allocate2DArrayPtr() is not working as I want to be clear on how to pass by pointers also. I do know how to change allocate2DArrayPtr() to return a pointer but I would like to pass the array as a parameter.
I am running the program on windows 7 using Codeblocks 13.12 IDE.
#include <iostream>
using namespace std;
void allocate2DArrayRef(int **&, int &, int &);
void allocate2DArrayPtr(int ***, int *, int *);
int main()
{
int sizeX, sizeY;
int **Array2D;
allocate2DArrayRef(Array2D, sizeX, sizeY);
for(int i=0; i< sizeX; i++)
{
for(int j=0; j< sizeY; j++)
{
cout << "Array2D[" << i << "][" << j << "]:" << Array2D[i][j] << endl;
}
}
cout << endl << endl;
int **secArray2D;
allocate2DArrayPtr(&secArray2D, &sizeX, &sizeY);
for(int i=0; i<sizeX; i++)
{
for(int j=0; j<sizeY; j++)
{
cout << "secArray2D[" << i << "][" << j << "]:" << secArray2D[i][j] << endl;
}
}
return 0;
}
void allocate2DArrayRef(int **&locArray, int& indexFirst, int& indexSecond)
{
indexFirst = 4;
indexSecond = 5;
locArray = new int*[indexFirst];
for(int i=0; i<indexFirst ; i++)
{
locArray[i] = new int[indexSecond];
for(int j=0; j<indexSecond; j++)
{
locArray[i][j] = i*j;
}
}
}
void allocate2DArrayPtr(int ***locArray, int *indexFirst, int *indexSecond)
{
*indexFirst = 2;
*indexSecond = 3;
int **temp = *locArray;
temp = new int*[*indexFirst];
for(int i=0; i<(*indexFirst) ; i++)
{
temp[i] = new int[*indexSecond];
for(int j=0; j<(*indexSecond); j++)
{
temp[i][j] = i+j;
}
}
}
The reason allocate2DArrayPtr does not work is you never set locArray to point to the array you create in the function. This means when you return from the function secArray2D still is uninitialized.
Adding
*locArray = temp;
To the end of allocate2DArrayPtr will fix the problem.
Or you can reference your to temp like this:
int **&temp = *locArray;
This is my first time here. I really hope anyone can help me out there. So this is my problem. I keep getting run time error #2 something about a corrupt "arr". But the program runs fine until the end. I can't figure it out.
This is my code:
#include <iostream>
using namespace std;
void main(){
int arr1[3];
int temp;
//INPUT NUMBERS
for (int i=0; i<5;i++)
{
cin>>arr1[i];
}
cout<<endl;
//SORT
for(int c=0;c<5;c++)
{
for (int k=0;k<5;k++)
{
if(arr1[c]<arr1[k])
{
temp=arr1[k];
arr1[k]=arr1[c];
arr1[c]=temp;
}
}
}
for (int m=0; m<5; m++)
{
cout<<arr1[m]<<endl;
}
}
Try this out:
#include <iostream>
using namespace std;
int main()
{
int arr1[5];
int temp;
//INPUT NUMBERS
for (int i = 0; i < 5; i++) {
cin >> arr1[i];
}
cout << endl;
//SORT
for (int c = 0; c < 5; c++) {
for (int k = 0; k < 5; k++) {
if (arr1[c] < arr1[k]) {
temp = arr1[k];
arr1[k] = arr1[c];
arr1[c] = temp;
}
}
}
for (int m = 0; m < 5; m++) {
cout << arr1[m] << endl;
}
}
It compiles properly without any errors. The mistake you had made is in declaring the size of the array. If you want to store 5 in puts, you need to declare an array of size 5. Your code might work, but a good compiler will always give out an error.
The reason being that when you declare an array, you actually create a pointer to the first element of the array. And then, some memory regions are kept for this array, depending on the size. If you try to access an element that is outside these memory regions, you may encounter a garbage value.
Here's your code in ideone.
#include <iostream>
#include <vector>
using namespace std;
class PerformSort
{
public:
const vector<int> * p;
vector<int>& getElements(int);
vector<int>& sortArray(vector<int>&);
void printer(vector<int>&);
}firstSort;
vector<int>& PerformSort::getElements (int num)
{
vector<int> elements(num);
for (int i = 0; i < num; i++)
{
cout << "Enter elements into the array: ";
cin >> elements[i];
}
p = &elements;
return p;
}
vector<int>& PerformSort::sortArray (vector<int>& vector)
{
int holder, min;
for (int i = 0; i < (sizeof(vector) - 1); i++)
{
min = i;
for (int j = (i + 1); j < sizeof(vector); j++)
{
if (vector[j] < vector[min])
{
min = j;
}
}
if (min != i)
{
holder = vector[i];
vector[i] = vector[min];
vector[min] = holder;
}
}
return vector;
}
void PerformSort::printer(vector<int>& vector2)
{
for (int i = 0; i < sizeof(vector2); i++)
{
cout << vector2[i] << " ";
}
}
int main ()
{
int numberOfTimes;
cin >> numberOfTimes;
firstSort.printer(firstSort.sortArray(firstSort.getElements(numberOfTimes)));
return 0;
}
This returns the error: "invalid initialization of reference of type from expression of type". My first approach to create a SelectionSort algorithm was to try passing the vector by value (stupidly). After this I started to use pointers instead, after some research. However, this resulted in the aforementioned error. Declaring everything as constant does not seem to resolve the underlying error, despite how, if I understand things correctly, the error lies with temporary references being passed where constant ones are required. Any thoughts on how I might achieve this passing and returning of vectors? (I come from a Java background and am just beginning C++, so forgive me if I have made any obvious errors with regards to the pointers).
Return it by value:
vector<int> PerformSort::getElements (int num)
{
vector<int> elements(num);
for (int i = 0; i < num; i++)
{
cout << "Enter elements into the array: ";
cin >> elements[i];
}
return elements;
}
This will also let you get rid of p, which is a huge can of worms in its own right.
Finally, I notice that you use sizeof(vector) in quite a few places. This won't give you the number of elements in the vector; use vector.size() instead.
Rename the variable vector to something else:
vector<int>& PerformSort::sortArray (vector<int>& wayBetterName)
&
return wayBetterName;
What urged you to name a variable the same as a type?
There's many more other issues with the code.
You don't need pointers, you don't need the references, plus you're better off just using std::sort.