Removing cout statement causing value change of a variable - c++

In the following code, when I'm removing cout statement (line after //******)then it is causing a change in the value of "i".
I used TDM-GCC 4.9.2 32 bit release and TDM-GCC 5.1.0 compilers.
I ran this code on codechef and there it runs fine and cout statement is not affecting the value of "i".
#include<iostream>
using namespace std;
int subset(int [], int);
int main()
{
int size,i,ans;
cout<<"size of array : ";
cin>>size;
int arr[size];
for(i = 0 ; i<size;i++)
{
cin>>arr[i];
}
ans = subset(arr,size);
cout<<"ans = "<<ans;
return 0;
}
int subset(int arr[], int size)
{
int i,j, tsum=0, completed=0;
for(i = 0 ;i<size;i++)
tsum = tsum + arr[i];
int carr[tsum+1],temp;
for(i=0;i<size;i++)
{
temp = arr[i];
carr[temp] = 1;
for(j=i+1;j<size;j++)
{
temp = temp + arr[j];
carr[temp] = 1;
}
}
for(i=1;i<=tsum;i++)
{
if(carr[i]!=1)
{
//************************************
cout<<"i : "<<i<<endl;
break;
}
}
return i;
}
Sample input :
size of array : 3
1
2
5
sample output without cout statement :
ans = 6
sample output having cout statement :
i : 4
ans = 4
Actual answere is 4 for the input.

The main problem seems to be that carr is uninitialized.
It is declared as
int carr[tsum+1]
with no initializer.
Later on some elements are set, but always to 1:
carr[temp] = 1;
In the last loop carr is examined:
if(carr[i]!=1)
This condition makes no sense. Either carr[i] has been set, then it is guaranteed to be 1, or it is uninitialized, in which case this comparison has undefined behavior.
Note that variable-length arrays are not standard C++.

To solve the problems as stated by Some Programmer Dude and melpomene, i.e. Variable-length arrays are not standard C++ and carr is uninitialized. Use c++ vectors and initialize them correctly. That would look something like this:
#include <iostream>
#include <vector>
using namespace std;
int subset(const std::vector<int>, const int);
int main()
{
int size, i, ans;
cout << "size of array : ";
cin >> size;
std::vector<int> arr(size);
for (i = 0; i < size; i++)
{
cin >> arr[i];
}
ans = subset(arr, size);
cout << "ans = " << ans;
return 0;
}
int subset(const std::vector<int> arr, const int size)
{
int i, j, tsum = 0, completed = 0;
for (i = 0; i < size; i++)
tsum = tsum + arr[i];
std::vector<int> carr(tsum + 1, 0);
int temp;
for (i = 0; i < size; i++)
{
temp = arr[i];
carr[temp] = 1;
for (j = i + 1; j < size; j++)
{
temp = temp + arr[j];
carr[temp] = 1;
}
}
for (i = 1; i <= tsum; i++)
{
if (carr[i] != 1)
{
//************************************
cout << "i : " << i << endl;
break;
}
}
return i;
}

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.)

Arrays aren't behaving as I'm expecting

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);
}
}

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;
}
}

Error implementing selection sort in C++

I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
I can't find the error. I'm new to C++.
Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below.
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
The resulting output was as follows:
-5 -4 -3 0 2 3 4 6 100 200
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.

Swapping Pointers of Array

#include <iostream>
#include <cstdlib>
using namespace std;
void swapNum(int *q, int *p)
{
int temp;
temp = *q;
*q = *p;
*p = temp;
}
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
int main()
{
const int size = 20;
int arr[size];
int *ip;
ip = arr;
cout << "Please enter 20 different numbers." << endl;
for (int i = 0; i < size; i++)
{
cout << "\nNumber " << i+1 << " = ";
cin >> ip[i];
}
reverse(ip, size);
cout << "I will now print out the numbers in reverse order." << endl;
for (int j = 0; j < size; j++)
{
cout << ip[j] << " ";
}
return 0;
}
When I try to run this program it crashes. I don't know what's wrong and the purpose of my program is to swap number of the array using pointers. I am recently introduced to this so I am not that familiar with it. But I think that I am swapping the address of the numbers instead of swapping the numbers in the address. Correct me if I am wrong.
You're accessing outside the array bounds in reverse() when you do:
swap(ip[k], ip[size-k]);
On the first iteration of the for loop, k is 0 and size-k is size. But array indexes run from 0 to size-1. So it should be:
swap(ip[k], ip[size-k-1]);
But I don't see a definition of swap in your program. I think it should actually be:
swapNum(&ip[k], &ip[size-k-1]);
Another improvement: Instead of handling size == k/2 specially and using break, just use size < k/2 as the bound test in the for loop.
swap(ip[k], ip[size-k]);
Your problem is there. size - k when k is 0 will lead to undefined behavior (accessing an array out of bounds). Your loop structure in reverse can be simplified:
for (int k = 0; k < size / 2; k++)
swapNum(&ip[k], &ip[size - k - 1]); // updated to use the address since your swap function takes pointers.
Function reverse is invalid
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
For example when k is equal to 0 then you call
swap(ip[0], ip[size]);
However the array has no element with index size.
ALso you mess two functions std::swap and swapNum
This code snippet also is invalid
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
When size is an even number (or an odd number) as in your code then you make incorrect swap. For example if size is equal to 20 then you should swap ip[9[ with ip[10]. However according to the code snippet above you swap ip[10] with ip[11].
You could use standard algorithm std::reverse
for example
#include <algorithm>
#include <iterator>
//...
std::reverse( std::begin( arr ), std::end( arr ) );
or
#include <algorithm>
//...
std::reverse( arr, arr + size );
If you want to write the function yourself then it could look as
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
int tmp = a[k];
a[k] = a[size-k-1];
a[size-k-1] = tmp;
}
}
Or if you want to use your function swapNum then
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
swapNum( &a[k], &a[size-k-1] );
}
}
EDIT: I removed qualifier const from the first parameter that was a typo.