How to fix this bug on sorting an array? - c++

#include <iostream>
using namespace std;
template <class T>
T sortArray(T data[])
{
int arrsize = sizeof(data)/sizeof(T);
int x,y,temp;
for(y=0;y<arrsize;y++)
{
for(x =0;x<arrsize-y-1;x++)
{
if(data[x]>data[x+1])
{
temp = data[x];
data[x] = data[x+1];
data[x+1] = temp;
}
}
}
return data;
}
int main()
{
int x;
int arr[] = {10,7,32,65,12,6};
int sorted[] = sortArray(arr[]);
for(x=0;x<6;x++)
{
cout<<sorted[x]<<endl;
}
}
When i try to sort compile this code i get an error of
**abc\main.cpp:34: error: expected primary-expression before ']' token
int sorted[] = sortArray(arr[]);
^**
How to fix this bug . if i remove [] i get more errors

Quite a lot wrong. Fixed it here:
#include <iostream>
using namespace std;
template <class T>
T* sortArray(T data[], int arrsize) // better pass the size of the array, and return T*
{
int x,y,temp;
for(y=0;y<arrsize;y++)
{
for(x =0;x<arrsize-y-1;x++)
{
if(data[x]>data[x+1])
{
temp = data[x];
data[x] = data[x+1];
data[x+1] = temp;
}
}
}
return data;
}
int main()
{
int x;
int arr[6] = {10,7,32,65,12,6};
int *sorted = sortArray(arr, sizeof(arr)/sizeof(arr[0])); // pass size of array
for(x=0;x<6;x++)
{
cout<<sorted[x]<<endl;
}
}
Output:
6
7
10
12
32
65

T sortArray(T data[])
is supposed to return a T, but you are useing an int array to catch it:
int sorted[] = sortArray(arr[]);
To work out, you can change this method to (you don't need to return it, i.e. removing the return line):
void sortArray(T data[])
and call it like:
sortArray<int>(arr);

The return type of sortArray is T but what you return is data of type T[]. You should change to the following prototype:
T* sortArray(T data[]);

You are doing bubble sort.
You need to fix the method signature as follows:
T * sortArray(T * data)
{
In the main(), you need to fix the calls:
int * sorted = sortArray(arr);
This should fix the errors. Basically, you are sending in a pointer to an array, and you want the method to return a pointer to a sorted array.

Related

Segmentation fault: 11 in C++ IntVector

I'm attempting to implement an intvector in C++ and am getting a "Segmentation fault: 11" error. I understand this has something to do with memory management, and considering how new I am to C++ it could definitely be a pretty minor mistake. I debugged the code with valgrind and was given messages such as the following:
Use of uninitialized value of size 8, Invalid read of size 4,Conditional jump or move depends on uninitialized value(s).
My best guess is it has something to do with how I'm implementing the arrays. I originally had the arrays stored on the heap but changed it to the stack and still got the same error. I've already implemented an intvector in java, so I was attempting to use similar logic here, which perhaps is part of the issue.
#include <iostream>
#include "IntVector.h"
#include <cmath>
using namespace std;
int num_elements = 0;
int array_size = 0;
int expansion_factor;
void IntVector::expandArray(){
int tempArr[array_size*2];
for(int i =0;i<array_size;i++){
tempArr[i] = array[i];
}
array = tempArr;
array_size = array_size * 2;
}
void IntVector::add(int val){
int tempArr[array_size];
if(array_size == num_elements){
expandArray();
array[num_elements] = val;
}
else{
for(int i = 0;i<array_size;i++){
tempArr[i] = array[i];
}
tempArr[num_elements] = val;
array = tempArr;
}
num_elements++;
}
void IntVector::remove(int index){
}
int IntVector::get(int index) const{
return index;
}
void IntVector::removeLast(){
}
void IntVector::set(int index, int val){
}
std::string IntVector::toString()const {
return "";
}
IntVector::IntVector(int initial_size){
int* array = new int[initial_size];
}
IntVector:: ~IntVector(){
delete[] array;
}
int main(){
IntVector v(0);
v.add(5);
}
#ifndef INTVECTOR_H_
#define INTVECTOR_H_
using std::cout;
class IntVector {
private:
int* array;
int num_elements;
int array_size;
int expansion_factor;
void expandArray();
public:
void add(int val);
void remove(int index);
int get(int index) const;
void removeLast();
void set(int index, int val);
std::string toString() const;
IntVector(int initial_size);
~IntVector();
};
#endif
As mention in the comments, there are definitely some holes in your understanding of C++. Really when dealing with header files you should have a main.cpp, someotherfile.h, someotherfile.cpp. That just best practices to avoid redefinition errors.
There was quite a bit wrong with the way you accessed the private variable. If a class has a private( or even public) variable you don't have to redeclare it each time you want to change its value.
There were one or two major flaws with the way you expanded the vector. If the vector size is initialized to 0 then 0*2 is still 0 so you never actually increased the size. Secondly, when you set the original array = to the new array the new array was just a local array. This means that the memory wasn't actually allocated permanently, once the function ended the temparr was destroyed.
I know this was probably a lot but if you have any question feel free to ask.
main.cpp
#include "IntVector.h"
int main()
{
IntVector v;
IntVector x(10);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.print();
cout << endl;
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.print();
return 0;
}
IntVector.h
#include <string>
#include <iostream>
using namespace std;
class IntVector {
private:
int *array;
int num_elements;
int array_size;
//int expansion_factor =; you would only need this if you plan on more than double the vector size
void expandArray(); //normally c++ array double in size each time they expand
public:
//Constructors
IntVector(); //this is a contructor for if nothing is called
IntVector(int initial_size);
//setters
void push(int val); //add
void pop(); //removelast
void remove(int index); //remove
void at(int index, int val); //set
//Getters
int at(int index);
//std::string toString(); I'm changing this to print
void print(); //will print the contents to the terminal
//Deconstructor
~IntVector();
};
IntVector.cpp
#include "IntVector.h"
//constructors
IntVector::IntVector() //no arguments given
{
array = new int[0];
num_elements = 0;
array_size = 0;
}
IntVector::IntVector(int initial_size)
{
array = new int[initial_size];
num_elements = 0;
array_size = initial_size;
}
void IntVector::expandArray()
{
int *tempArr;
if(array_size == 0){
array_size = 1;
tempArr = new int[1];
} else {
//make sure to allocate new memory
//you were creating a local array which was destroy after the function was completed
//using new will allow the array to exist outside the function
tempArr = new int[array_size * 2];
}
for (int i = 0; i < array_size; i++)
{
tempArr[i] = array[i];
}
//make sure to delete the old array otherwise there is a memory leak.
//c++ doesn't have a garbage collector
delete[] array;
array = tempArr;
array_size = array_size * 2;
}
void IntVector::push(int val)
{
num_elements++;
//checking if vector needs to increase
if (array_size <= num_elements)
{
expandArray();
array[num_elements-1] = val;
}
else
{
array[num_elements-1] = val;
}
}
void IntVector::remove(int index)
{
//not sure how to implment this becuase each element has to be a number.
}
int IntVector::at(int index)
{
return array[index];
}
void IntVector::pop()
{
num_elements = num_elements-1; //not really removing it from the "vector" but it won't print out again
}
void IntVector::at(int index, int val)
{
array[index] = val;
}
void IntVector::print()
{
for (int i = 0 ; i < num_elements; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
IntVector::~IntVector()
{
delete[] array;
}
output
5 5 5 5 5
5 5 5 5 5
Hopefully, the comments help. I changed the name of the functions to better match the actual vecter class the already exists in C++. I think it's good to pick apart already defined functions like this because you get a better understanding of how they actually work and not just how to use them.
If you got any questions just leave a comment

How to give an array of templates as a parameter in a function?

I was studying for my C++ exam and noticed that my answer differs from the solution. The question was to write a method that gives the biggest double or string (by size) from an array with templates. I know that by passing the array as a parameter you give a pointer to the first index.
I'm really confused on where I should write the "const" to signify that the array is not being altered though. Also the code contains 2 dutch words, "grootste" means "biggest", and "grootte" just means "size". PS: max= maximum
this is my solution:
#include <iostream>
using namespace std;
template <typename T>
T grootste(T const [],int);
double grootte(double);
int grootte(const string&);
int main(){
double getallen[5] = {5.5,7.7,2.2,9.8,9.9};
string woorden[3] = {"geloof","hoop","de liefde"};
cout << "Biggest number " << grootste(getallen,5) << "." << endl;
cout << "Longest of 3 strings " << grootste(woorden,3) << "." <<
endl;
return 0;
}
int grootte(const string &a){
return a.size();
}
double grootte(double d){
return d;
}
template <typename T>
T grootste (T const arr[], int lengte){
T max=arr[0];
for(int i=1;i<lengte;i++){
if(grootte(arr[i])>grootte(max)){
max = arr[i];
}
}
return max;
}
this is the solution my course gives me, there was no main included and the other methods were the same.
I wrote the solution again but now it's a literal copy from the pdf the students recieved. I'm sorry for the spacing, i have no idea why it does that.
template < class T >
T grootste ( const T * array , int lengte ){
T gr = array [0];
for ( int i =1; i < lengte ; i ++) {
if ( grootte ( gr ) < grootte ( array [i ]) ){
gr = array [i ];
}
}
return gr ;
}
These parameters are all equivalent:
const T p[]
T const p[]
const T *p
T const *p
Which one to choose is a matter of taste and convention.
I always get confused when types get complex. Use a typedef/using statement to make it clear what you mean exactly.
using intptr = int*; //pointer to int
void foo(const intptr arr ) { // a const pointer to int
arr[0] = 32;
// arr = nullptr; //This will fail
}
using cint = const int;
void bar(cint* arr){ // pointer to const int
//arr[0] = 42; //This will fail
arr = nullptr;
}
template<class T>
struct Types {
using Tptr = T*;
using ConstT = const T;
};
template<class T>
T grootste(typename Types<T>::constT* arr, int length) { //pointer to const T, i.e Ts in the array cannot change
//...
}

How to set individual class array elements using class methods?

I'm using C++ and am trying to set an array element values with a setter method. The array is a class private member:
class Boo{
private:
int *x;
public:
Boo();
~Boo();
void setX(int,int);
int getX(int);
}
Boo::Boo(){
x = new int[1];
x = 0;
}
void Boo::setX(int value, int index){
//set condition for NULL
x[index] = value;
}
int Boo::getX(int index){
if(x[index] == NULL) {cout<<"invalid index"<<end; return;}
return x[index];
}
void test(){
Boo *p = new Boo();
p->setX(12,0);
cout<<p->getX(0)<<endl;
}
I been trying to test setting the values in 'x' starting with index '0' (like test()) but it crashes. I wanted to write a program where I run a loop counting up, and I set the array values. Can this be accomplish this way?
Do not use new in C++!
In this case, you should use std::vector<int>.
If you want to fix your code unless use std::vector,
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <memory>
using std::size_t;
class Boo {
private:
int *x;
size_t size;
size_t capacity;
public:
Boo();
~Boo();
void setX(int,size_t);
int getX(size_t);
};
Boo::Boo() : size(), capacity(1) {
this->x = new int[1];
//x = 0;//DO NOT ASSIGN NULL POINTER!!!!
}
Boo::~Boo() noexcept {
delete[] x;
}
void Boo::setX(int value, size_t index){
if(this->capacity <= index) throw std::out_of_range("Boo::setX");//YOU MUST CHECK RANGE
this->x[index] = value;
++this->size;
}
int Boo::getX(size_t index){
if(this->size <= index) throw std::out_of_range("Boo::getX");//YOU MUST CHECK RANGE
return x[index];
}
void test(){
auto p = std::make_unique<Boo>();
p->setX(12,0);
std::cout << p->getX(0) << std::endl;
}
int main(){
test();
}
http://melpon.org/wandbox/permlink/aIhwC5c9o1q8ygIo
Boo::Boo()
{
x = new int[1];
x = 0;
}
you are not able to set value in an array because after initializing with memory, you have set the pointer of an array to null in constructor.
please use x[0] = 0; instead of x = 0;

How can I access a member of a class from a function via pointer?

I wish to
create an array of class/struct items (c1)
then create an array of pointer to the original array (*cp1), which can be sorted
then access members of the class from within a function.
However I'm getting stuck at the initial function call.
Here's my basic code:
struct Car
{
int speed;
};
Car c1[5];
Car *cp1[5];
int main() {
for (int i=0;i<5;i++) {
c1[i].speed = i;
cp1[i] = &c1[i];
}
garage(cp1, 5);
}
void garage(Car **ar, int n) {
int p = (*ar[n / 2])->speed;
}
First of all, your garage function is not known to the compiler at the place where you call it, since it is defined below main. To fix it, either place the function definition above main, or introduce it with a prototype.
Second, at the line int p = (*ar[n / 2])->speed;, *ar[n/2] is not a pointer, so you should use . instead of ->, as in int p = (*ar[n / 2]).speed;
Funcion garage must be declared before you can refer it.
void garage(Car **ar, int n);
int main()
{
//...
}
void garage(Car **ar, int n) {
//...
}
Function main in C++ shall have return type int
int main()
{
//...
}
And within the function the correct expression will look
void garage(Car **ar, int n) {
int p = (*ar )[n / 2]).speed;
}
Or
void garage(Car **ar, int n) {
int p = ar[n / 2]->speed;
}
Or
void garage(Car **ar, int n) {
int p = ( *ar[n / 2] ).speed;
}
struct Car
{
int speed;
};
Car c1[5];
Car *cp1[5];
void garage(Car **ar, int n); // forward declare garage
int main()
{
for (int i=0;i<5;i++) {
c1[i].speed = i;
cp1[i] = &c1[i];
}
garage(cp1, 5);
}
void garage(Car **ar, int n) {
int p = ar[n / 2]->speed; // -> dereferences the pointer, you don't need to
}

Memory leak in code snippet

I'm trying to dust off my C++. I knocked together a simple program to find the Fibonacci sequence with memoization. There's a memory leak, and I can't seem to figure out why. The leak is reported in Fibonacci::setToFind.
Sorry for the long code chunk, but I couldn't figure out how to make a more minimal reproducible example.
#include <iostream>
class Fibonacci
{
public:
int m_valuefound;
int m_tofind;
long int *m_memo;
int findValue(int value){
if (m_memo[value] == 0) {
if (value == 0 || value == 1) {
m_memo[value] = 1;
} else {
m_memo[value] = findValue(value-1) + findValue(value-2);
}
}
return m_memo[value];
}
void setToFind(int value){
m_tofind = value;
m_memo = new long int[value];
std::fill_n(m_memo,value,0);
}
void solve(){
int value = m_tofind;
int result = findValue(value);
std::cout<< "Value is: " << result << std::endl;
}
~Fibonacci(){};
};
int main (int argc, char * const argv[]) {
std::cout << "Enter integer values until you'd like to quit. Enter 0 to quit:";
int user_ind=0;
// for testing non-interactivly
while(true){
for (user_ind=1; user_ind<45; user_ind++) {
Fibonacci *test = new Fibonacci;
test->setToFind(user_ind);
test->solve();
delete test;
}
}
return 0;
}
You never delete m_memo in the destructor of Fibonacci.
Since you're allocating m_memo as an array, you should delete with delete[] m_memo
Here is working code with a non-copyable Fibonacci class. Why don't
you allocate the memory in the constructor. Use RAII wherever possible
and remember The Rule of Five. Avoid all of this in the first place by
using std::vector.
#include <iostream>
class Fibonacci
{
public:
int m_valuefound;
int m_tofind;
long int *m_memo;
int findValue(int value){
if (m_memo[value] == 0) {
if (value == 0 || value == 1) {
m_memo[value] = 1;
} else {
m_memo[value] = findValue(value-1) + findValue(value-2);
}
}
return m_memo[value];
}
void setToFind(int value){
m_tofind = value;
m_memo = new long int[value];
std::fill_n(m_memo,value,0);
}
void solve(){
int value = m_tofind;
int result = findValue(value);
std::cout<< "Value is: " << result << std::endl;
}
// why don't you allocate in the constructor?
Fibonacci() : m_valuefound(0), m_tofind(0), m_memo(nullptr) {}
~Fibonacci() {
delete[] m_memo;
};
// make the class non-copyable
Fibonacci(const Fibonacci&) = delete;
const Fibonacci& operator=(const Fibonacci&) = delete;
/*
C++03 non-copyable emulation
private:
Fibonacci(const Fibonacci&);
const Fibonacci& operator=(const Fibonacci&);
*/
};
You are allocating m_memo in setToFind:
m_memo = new long int[value];
but your destructor does not have a delete [] m_memo. You should initialize m_memo in your constructor and make you class non-copyable by disabling your copy constructor and assignment operator using delete if using C++11:
Fibonacci(const Fibonacci&) = delete;
const Fibonacci& operator=(const Fibonacci&) = delete;
Otherwise you can make them private. If you used a container such as std::vector your life would be much simpler.
I suggest you use more the STL algorithms. Here's a code snippet with a rather not optimized functor but you can get the idea of the power of the STL:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Fibonacci
{
public:
Fibonacci();
~Fibonacci() {}
int operator()();
private:
int n0_;
int n1_;
int n_;
};
Fibonacci::Fibonacci():n0_(0),n1_(1),n_(0)
{
}
int Fibonacci::operator()()
{
if(n_ > 1)
return (++n0_) + (++n1_);
else
return ++n_;
}
using namespace std;
int main()
{
Fibonacci func;
vector<int> v;
//generate 100 elements
generate_n(v.begin(),100,func);
//printing the values using a lambda expression
for_each(v.begin(),v.end(),[](const int val){cout << val << endl;});
return 0;
}
You can then apply the finding algorithm you want on the vector using find_if and defining your own functor.