Arrays aren't behaving as I'm expecting - c++

Pointers are still a little confusing to me. I want the split function to copy negative elements of an array into a new array, and positive elements to be copied into another new array. A different function prints the variables. I've included that function but I don't think it is the problem. When the arrays are printed, all elements are 0:
Enter number of elements: 5
Enter list:1 -1 2 -2 3
Negative elements:
0 0
Non-Negative elements:
0 0 0
I assume that the problem is that in the split function below i need to pass the parameters differently. I've tried using '*' and '**' (no quotes) for passing the parameters but I get error messages, I may have done so incorrectly.
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
alpha[i] = bravo[a];
++a;
}
else {
alpha[i] = charlie[b];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}
my main function (all arrays are required to be pointers):
int num_elements;
cin >> num_elements;
int * arr1 = new int[num_elements];
int x;
cout << "Enter list:";
for (int i = 0; i < num_elements; ++i) {
cin >> x;
arr1[i] = x;
}
int y = 0;
int z = 0;
count(arr1, num_elements, y, z);
int * negs = new int [y];
int * nonNegs = new int[z];
split(arr1, negs, nonNegs, num_elements, y, z);
cout << "Negative elements:" << endl;
print_array(negs, y);
cout << endl;
cout << "Non-Negative elements:" << endl;
print_array(nonNegs, z);
cout << endl;
All functions:
void count(int A[], int size, int & negatives, int & nonNegatives) {
for (int i = 0; i < size; ++i) {
if (A[i] < 0) {
++negatives;
}
if (A[i] >= 0) {
++nonNegatives;
}
}
}
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
alpha[i] = bravo[a];
++a;
}
else {
alpha[i] = charlie[b];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}
void print_array(int A[], int size) {
for (int i = 0; i < size; ++i) {
cout << A[i] << " ";
}
}
All help is appreciated.
EDIT: I apologize for my unclear question, I was wondering how to get my arrays to behave as I want them to.

Array is behaving correctly as per instruction :), you are doing minor mistake (may be overlook) in split function. I have commented out the statement and given reason of problem, please correct those two line of code, rest is fine.
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
//alpha[i] = bravo[a];// here alpha is your source array, don't overwrite it
bravo[a] = alpha[i];
++a;
}
else {
//alpha[i] = charlie[b];// here alpha is your source array, don't overwrite it
charlie[b] = alpha[i];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}

Related

C6385 warning in VS (in regard to dynamic arrays)

My code is supposed to print the Union and Intersection of two sets of integers.
Why do I get this warning?
Is it because I use dynamic arrays and it's size could be anything in runtime?
How can I fix it? My code works fine but this warning really bugs me.
P.S: I know it would be a lot easier to use std::vector but my teacher required to use arrays.
#include <iostream>
using namespace std;
void UnionFunc(int[],int,int[],int,int[],int&);
void IntersectionFunc(int[], int, int[], int, int[], int&);
int main() {
int* A;
int SizeA;
int* B;
int SizeB;
int* Union;
int UnionSize=0;
int* Intersection;
int IntersectionSize=0;
cout << "Enter the Size of First Set : "; cin >> SizeA;
A = new int[SizeA];
cout << "Enter the Size of Second Set : "; cin >> SizeB;
B = new int[SizeB];
Intersection = new int[SizeA >= SizeB ? SizeB : SizeA];
Union = new int[SizeA + SizeB];
for (int i = 0; i < SizeA; i++) {
cout << "Set A[" << i + 1 << "] = ";
cin >> A[i];
}
for (int i = 0; i < SizeB; i++) {
cout << "Set B[" << i + 1 << "] = ";
cin >> B[i];
}
UnionFunc(A,SizeA,B,SizeB,Union,UnionSize);
IntersectionFunc(A, SizeA, B, SizeB, Intersection, IntersectionSize);
cout <<endl<< "Union Set : ";
for (int i = 0; i < UnionSize; i++) {
cout << Union[i] << ",";
}
cout <<endl <<"Intersection Set : ";
for (int i = 0; i < IntersectionSize; i++) {
cout << Intersection[i] << ",";
}
system("pause>n");
return 0;
}
void UnionFunc(int A[],int SizeA, int B[],int SizeB, int Union[],int &UnionSize) {
//Adding First Array to Union Array
for (int i = 0; i < SizeA;i++) {
Union[i] = A[i];
UnionSize++;
}
//Checking if second array's elemnts already exist in union arry, if not adding them
bool exist;
for (int i = 0; i < SizeB; i++) {
exist = false;
for (int j = 0; j < UnionSize; j++) {
if (B[i] == Union[j] ) {
exist = true;
}
}
if (exist == false) {
Union[UnionSize] = B[i];
UnionSize++;
}
}
}
void IntersectionFunc(int A[], int SizeA, int B[], int SizeB, int Intersection[], int& IntersectionSize) {
for (int i = 0; i < SizeA; i++) {
for (int j = 0; j < SizeB; j++) {
if (A[i] == B[j]) {
Intersection[IntersectionSize] = A[i];
IntersectionSize++;
}
}
}
}
Is it because I use dynamic arrays and it's size could be anything in
runtime?
Yes! The compiler doesn't know (and, as your code is written, can't know) that both SizeA and SizeB will be 'valid' numbers - so the size of the three int arrays you create could be less than is required for the Intersection[i] 'read' to be valid.
A 'quick and dirty' fix for this is to provide a visible guarantee to the compiler that the arrays you create will be at least a certain size, like this:
A = new int[max(1,SizeA)]; // Compiler can now 'see' a minimum size
And similarly for the other allocations you make with the new[] operator.
(I have tested this with VS2019, adding the max(1,SizeA) and max(1,SizeB) 'fixes' to just the allocations of A and B and the warning is removed.)

Can't figure out why my Print Array is replacing elements

I'm taking a C++ class and we've gotten to pointers. The assignment we've been given is to basically bubble sort an array that was read from a text file by passing pointers as parameters for various functions. I think I have a decent setup that outputs what I'm looking for, but for specific actions, I'm getting a zero as an element when there isn't one written to the array.
#include <iostream>
#include <fstream>
using namespace std;
int capacity;
int count;
int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);
int main() {
int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);
return 0;
}
int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bsort(int *arr, int last) {
int i, j;
bool swapped;
for (i = 0; i < last + 1; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
void writeToConsole(int *arr, int last) {
cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}
void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j;
bool swapped;
for (i = 0; i < last; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1]))
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int ascending(int a, int b){
return a > b;
}
int descending(int a, int b){
return a < b;
}
My output looks like this:
Raw array data:
[ 8 4 7 2 9 5 6 1 3 ]
After simple bubble sort:
[ 0 1 2 3 4 5 6 7 8 ]
Now descending:
[ 9 8 7 6 5 4 3 2 1 ]
Any ideas as to why my second sort is throwing in a zero? Thank you!
you have to do this change is in bubble_sort function
for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}

Dynamic allocation of an array into a function with pointer parameters

I am having issues finishing passing an array via pointers through a series of functions. I create a function using dynamic allocation to create it. Even though that is successful I cannot get it to pass through functions that take pointers as arguments. The functions return the mean median and mode and have been completed. However I cannot pass them when converting them into pointer syntax. Thanks for the help in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
int students;
int * studentarray;
int stumode;
double stuavg;
int stumed;
int arr;
int mode(int *[], int );
double average(int *[], int);
double median(int *[], int);
void selectSort(int [], int);
void swap(int *, int *);
int makeArray(int*, int);
int main()
{
studentarray = &arr;
cout << "How many students are there?" << endl;
cin >> students;
makeArray(studentarray, students);
for (int i = 0; i < students; i++) {
cout << "How many movies did student " << i + 1 << " view?" << endl;
cin >> studentarray[i];
}
selectSort(studentarray, students);
stumode = mode(&studentarray, students);
stuavg = average(&studentarray, students);
stumed = median(&studentarray, students);
cout << "The array has been sorted in ascending order." << endl;
cout << "The mode is " << stumode << "." << endl;
cout << "The mean is " << stuavg << "." << endl;
cout << "The median is " << stumed << "." << endl;
delete[] studentarray;
return 0;
}
int mode(int *arr, int size)
{
if (size <= 0) return 0;
int most = 0, position = 0, most_count = 0;
int counter = 1;
for (int i = 1; i < size; i++)
{
if (* (arr + i) != * (arr + position) )
{
if (counter > most)
{
most = counter;
most_count = 0;
}
else if (counter == most) most_count++;
position = i;
counter = 0;
}
else counter++;
}
if (most_count) return 0;
else return * ( arr + position );
}
double average(int *arr, int size)
{
if (size <= 0) return 0;
int total = 0;
for (int i = 0; i < size; i++) {
total += *(arr + i);
}
return (double)total / size;
}
double median(int *arr, int size)
{
if (size <= 0) return 0;
if (size % 2 == 0)
return (double) (* (arr + (size + 1) / 2));
else {
int mid = size / 2;
return (double)(* (arr + mid) + * (arr + mid + 1) / 2);
}
return 0;
}
void selectSort(int arr[], int size)
{
int min;
for (int i = 0; i < size - 1; i++)
{
min = i;
for (int j = i + 1; j < size; j++)
{
if ( arr[j] < arr[min])
{
min = j;
}
}
swap(&arr[min], &arr[i]);
}
}
void swap(int *one, int *two) {
int temp = *one;
*one = *two;
*two = temp;
}
int makeArray(int *arr, int size)
{
arr = new int[size];
return *arr;
}
Your implementation of makeArray is not right.
int makeArray(int *arr, int size)
{
// Allocates memory and assigns it to arr.
// This is a local change to arr. The value of the variable in
// main remains unchanged.
arr = new int[size];
// Returns an uninitialized value.
return *arr;
// The memory allocated in the previous line is now a memory leak.
}
You can make it simpler by using:
int* makeArray(int size)
{
return new int[size];
}
and use it in main as:
arr = makeArray(students);
However, I don't see how that is better than using:
arr = new int[students];
If you do that, makeArray becomes unnecessary. If makeArray needs to have additional code to fill up the array with some values, it will be useful. Otherwise, it does not add any useful functionality to your program.
Having said all of that, it is better to use std::vector instead of managing dynamically allocated memory in your own code. You would use:
std::vector<int> arr(students);
PS
I did not go through rest of your code. There might be other errors.

heapsort-code is not working

The following code is not working for heap sort. It looks ok to me. Can someone help me please? I have followed the pseudo code from CLRS, the sorted numbers are not being updated after the algorithm is traversed.
#include <iostream>
using namespace std;
void max_heapify(int *b, int i,int he_size)
{
int l,r,largest;
l=2*i;
r=(2*i+1);
if (l<=he_size && b[l]>b[i])
largest=l;
else largest=i;
if (r<=he_size && b[r]> b[largest])
largest=r;
if (largest!=i)
{
swap(b[i],b[largest]);
max_heapify(b,largest,he_size);
}
}
void build_max_heap(int *c,int h_size,int strlength)
{
for (int q=(strlength)/2;q==1;--q)
{
max_heapify(c,q,h_size);
}
}
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
int main()
{
int length;
int heap_size;
cout<<"Enter the number of numbers to be sorted by heap sort"<<endl;
cin>>length;
int* a=NULL;
a=new int[length-1];
int temp;
cout<<"Enter the numbers"<<endl;
for(int i=0;i<length;i++)
{
cin>>temp;
*(a+i)=temp;
}
cout<<"The given numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
heap_size= length;
build_max_heap(a,heap_size,length);
for (int l=length;l==2;--l)
{
swap(a[1],a[length]);
heap_size=heap_size-1;
max_heapify(a,1,heap_size);
}
cout<<"The sorted numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
system("pause");
return 0;
}
The number of mistakes in your code is enormous. Sorry to say it.
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
does nothing - a and b should be passed by link, not by value:
void swap(int &a, int &b)
{
int c=b;
b=a;
a=c;
}
for (int q=(strlength)/2;q==1;--q) is wrong. You meant for (int q=(strlength)/2;q>1;--q). Your loop is running only when q==1.
a=new int[length-1]; The size of array should be length, not length-1. And even though swap(a[1],a[length]); is wrong, because a[length] is out of array.
Also there are some mistakes in algorithm. I tried to rewrite as less code as possible.
Right code is:
#include <iostream>
using namespace std;
void sift_down(int *a, int start, int end) {
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int sw = root;
if (a[sw] < a[child])
sw = child;
if (child + 1 <= end and a[sw] < a[child + 1])
sw = child + 1;
if (sw == root)
return;
else
swap(a[root], a[sw]);
root = sw;
}
}
void max_heapify(int *b, int count) {
int start = (count - 2) / 2;
while (start >= 0) {
sift_down(b, start, count - 1);
--start;
}
}
void swap(int &a, int &b) {
int c = b;
b = a;
a = c;
}
int main() {
int length;
int heap_size;
cout << "Enter the number of numbers to be sorted by heap sort" << endl;
cin >> length;
int *a = new int[length];
cout << "Enter the numbers" << endl;
for (int i = 0; i < length; i++) {
cin >> a[i];
}
cout << "The given numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
heap_size = length;
max_heapify(a, heap_size);
--heap_size;
while (heap_size) {
swap(a[heap_size], a[0]);
--heap_size;
sift_down(a, 0, heap_size);
}
cout << "The sorted numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
//system("pause");
return 0;
}

Program gives a weird runtime error

#include<iostream>
using namespace std;
class darray
{
private:
int n; // size of the array
int *a; // pointer to the 1st element
public:
darray(int size)
{
n = size;
a = new int[n];
}
~darray(){ delete[] a; }
void get_input();
int get_element(int index);
void set_element(int index, int value);
int count(){ return n; }
void print();
};
void darray::get_input()
{
for (int i = 0; i < n; i++)
{
cin >> *(a + i);
}
}
int darray::get_element(int index)
{
if (index == -1)
index = n - 1;
return a[index];
}
void darray::set_element(int index,int value)
{
a[index] = value;
}
void darray::print()
{
for (int i = 0; i < n; i++)
{
cout << a[i];
if (i < (n - 1))
cout << " ";
}
cout << endl;
}
// perform insertion sort on the array a
void insertion_sort(darray d)
{
int v = d.get_element(-1); // v is the right-most element
int e = d.count() - 1; // pos of the empty cell
// shift values greater than v to the empty cell
for (int i = (d.count() - 2); i >= 0; i--)
{
if (d.get_element(i) > v)
{
d.set_element(e,d.get_element(i));
d.print();
e = i;
}
else
{
d.set_element(e, v);
d.print();
break;
}
}
}
int main()
{
int s;
cin >> s;
darray d(s);
d.get_input();
insertion_sort(d);
system("pause");
return 0;
}
I use the darray class to make a array of size n at runtime. This class gives basic functions to handle this array.
This programs says debugging assertion failed at the end.
It gives this error after ruining the program.Other than that the program works fine. What is the reason for this error ?
You need to declare and define a copy constructor:
darray::darray(const darray& src)
{
n = src.n;
a = new int[n];
for (int i = 0; i < n; i++)
{
*(a + i) = *(src.a + i);
}
}