Error accessing memory(heap) in a simply programm - c++

When I populate the array(doska) all is ok, but when I try to print element(cout<< I get error
#include <iostream>
using namespace std;
struct doskas{
int number;
char ch;
};
int main(){
auto doska= new doskas[8][8];
auto ss="0abcdefgh";
for(int i=1;i<=8;i++){
for(int j=1;j<=8;j++){
doska[i][j].ch=ss[i];
doska[i][j].number=j;
}
}
for(int i=1;i<=8;i++)
for(int j=1;j<=8;j++){
cout<<doska[i][j].ch;//ERROR
cout<<doska[i][j].number;
}
system("pause");
return 0;
}

Try from 0 and strictly less than 8, not from one to eight.

Array indices must always start with 0 and end with N-1 where N is the size of the array. Please change your index variables in all the for loops accordingly. Like this:
for(int i=0;i<8;i++)
{
//etc
}

You just have to enumerate array indices in the half-open range [0, N), and all is well:
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
doska[i][j].ch = ss[i];
doska[i][j].number = j;
}
}
See Dijkstra's famous argument on why this is the sanest way to think about ranges.

Related

Why does the compiler skip the for-loop?

I have tried to do some practice with vector, and I made a simple for loop to calculate the sum of the elements within the vector. The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for loop altogether, and I have not come up with a reasonable explanation.
//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;
int simplefunction(vector<int>vect)
{
int size = vect.size();
int sum = 0;
for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
{
sum = sum + vect[count];
}
return sum; //<<---the return sum is 0
}
int main()
{
vector<int>myvector(10);
for (int i = 0; i == 10; i++)
{
myvector.push_back(i);
}
int sum = simplefunction(myvector);
cout << "the result of the sum is " << sum;
return 0;
}
I have done some research, and usually the ill-defined for loop shows up when the final condition cannot be met (Ex: when setting count-- instead of count++)
Your loop's conditions are wrong, as they are always false!
Look at to the loops there
for (int i = 0; i == 10; i++)
// ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
and
for (int count=0; count==4; count++)
// ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
you are checking i is equal to 10 and 4 respectively, before incrementing it. That is always false. Hence it has not executed further. They should be
for (int i = 0; i < 10; i++) and for (int count=0; count<4; count++)
Secondly, vector<int> myvector(10); allocates a vector of integers and initialized with 0 s. Meaning, the loop afterwards this line (i.e. in the main())
for (int i = 0; i == 10; i++) {
myvector.push_back(i);
}
will insert 10 more elements (i.e. i s) to it, and you will end up with myvector with 20 elements. You probably meant to do
std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++)
{
myvector.push_back(i);
}
or simpler using std::iota from <numeric> header.
#include <numeric> // std::iota
std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);
As a side note, avoid practising with using namespace std;

Fill 2D vector in C++

I'm trying to fill 2D vector in C++ with characters, but when I run this code it ends with one line characters (*..).
How can I fill 2D vector like this:
*.*
.**
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<char> > vec2D;
std::vector<char> rowV;
unsigned int row=2;
unsigned int col=3;
char c;
unsigned int temp=0;
while(temp!=col)
{
while(rowV.size()!=row)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
++temp;
}
return 0;
}
You should clear rowV after each insertion, otherwise it will be full and no other characters will be added. Also, row should be swapped by col and vice-versa, otherwise you will get a 3x2 (and not 2x3) 2D vector.
while(temp!=row)
{
while(rowV.size()!=col)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
rowV.clear(); // clear after inserting
++temp;
}
It helps to know what [pushing back a 2DVector with an empty 1D vector] looks like.
See the example below.
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
//-v-----A FUNCTION TO PRINT 2D VECTORS
template<typename T> //We don't know what type the elements are yet, so we use a template
void printVec2D(vector<vector<T>> a) // a is the name of our input 2Dvector of type (T)
{
for (int i = 0; i < a.size(); i++) {// a.size() will equal the number of rows (i suppose rows/columns can depend on how you look at it)
for (int j = 0; j < a[i].size(); j++) {// a[i].size() is the size of the i'th row (which equals the number of columns, foro a square array)
std::cout << a[i][j] << "\t";
}
std::cout << "\n";
}
return;
}
//-^--------
int main()
{
int X = 3; int Y = 3;
int VectorAsArray[3][3] = {{1,2,3},
{14,15,16},
{107,108,109}};
vector<vector<int>> T;
for (int i = 0; i < X; i++)
{
T.push_back({});// We insert a blank row until there are X rows
for (int j = 0; j < Y; j++)
{
T[i].push_back(VectorAsArray[i][j]); //Within the j'th row, we insert the element corresponding to the i'th column
}
}
printVec2D(T);
//system("pause"); //<- I know that this command works on Windows, but unsure otherwise( it is just a way to pause the program)
return 0;
}

Equal elements in an unsorted array

I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other
bool pair(const int array[])
{
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
}
Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?
edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.
I was not trying to compile the code, for the record.
It will do neither:
i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.
If you really cant sort the array (which would be so easy with std::sort) then you can do this:
const int NumCards = 9; // If this is a constant, this definition should occur somewhere.
bool hasPair(const int array[], const int arraySize) {
int possibleCards[NumCards] = {0}; // Initialize an array to represent the cards. Set
// the array elements to 0.
// Iterate over all of the cards in your hand.
for (int i = 0; i < arraySize; i++) {
int myCurrentCard = array[i]; // Get the current card number.
// Increment it in the array.
possibleCards[myCurrentCard] = possibleCards[myCurrentCard] + 1;
// Or the equivalent to the above in a single line.
possibleCards[array[i]]++; // Increment the card so that you
// count how many of each card is in your hand.
}
for (int i = 0; i < NumCards; ++i) {
// If you want to check for a pair or above.
if (possibleCards[i] >= 2) { return true; }
// If you want to check for exactly a pair.
if (possibleCards[i] == 2) { return true; }
}
return false;
}
This algorithm is actually called the Bucket Sort and is really still sorting the array, its just not doing it in place.
do you know the meaning of return keyword? return means reaching the end of function, so in your code if two adjacent values are equal it immediately exits the function; if you want to continue checking for other equality possibilities then don't use return but you can store indexes of equal values in an array
#include <iostream>
using namespace std;
int* CheckForPairs(int[], int, int&);
int main()
{
int array[ ]= {2, 5, 5, 7, 7};
int nPairsFound = 0;
int* ptrPairs = CheckForPairs(array, 5, nPairsFound);
for(int i(0); i < nPairsFound; i++)
{
cout << ptrPairs[i] << endl;
}
if(ptrPairs)
{
delete[] ptrPairs;
ptrPairs = NULL;
}
return 0;
}
int* CheckForPairs(int array[] , int size, int& nPairsFound)
{
int *temp = NULL;
nPairsFound = 0;
int j = 0;
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
nPairsFound++;
}
temp = new int[nPairsFound];
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
{
temp[j] = i;
j++;
}
}
return temp;
}
You could use a std::unordered_set for a O(n) solution:
#include <unordered_set>
using namespace std;
bool hasMatchingElements(const int array[], int arraySize) {
unordered_set<int> seen;
for (int i = 0; i < arraySize; i++) {
int t = array[i];
if (seen.count(t)) {
return true;
} else {
seen.insert(t);
}
}
return false;
}
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
This loop will only compare two adjacent values so the loop will return false for array[] = {2,3,2,4,5}.
You need a nested for loop:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int unsortedArray[] = {2,3,2,4,5};
int size = 5;
for(int i=0;i<size-1;i++)
{ for(int j=i+1;j<size;j++)
{ if(unsortedArray[i]==unsortedArray[j])
{ printf("matching cards found\n");
return 0;
}
}
}
printf("matching cards not found\n");
return 0;
}
----EDIT------
Like Ben said, I should mention the function above will only find the first instance of 2 matching cards but it can't count how many cards match or if there are different cards matching. You could do something like below to count all the number of matching cards in the unsortedArray and save those values into a separate array. It's messier than the implementation above:
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#defin NUM_CARDS 52;
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,i,j;
cin>>N;
int unsortedArray[N];
for(int i=0;i<N;i++)
cin>>unsortedArray[i];
int count[NUM_CARDS]={0};
int cnt = 0;
for( i=0;i<N-1;i++)
{
for( j=i+1;j<N;j++)
{ if(unsortedArray[i]==-1)
break;
if(unsortedArray[i]==unsortedArray[j])
{
unsortedArray[j]=-1;
cnt++;
}
}
if(unsortedArray[i]!=-1)
{
count[unsortedArray[i]]=cnt; //in case you need to store the number of each cards to
// determine the poker hand.
if(cnt==1)
cout<<" 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else if(cnt>=2)
cout<<" more than 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else
cout<<" no matching cards of "<<unsortedArray[i]<<" was found"<<endl;
cnt = 0;
}
}

selection sort array run time error

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.

vector subscript out of range error in c++

I am trying to write a program that takes an input of of n integers, and finds out the one that occurs the maximum number of times in the given input. I am trying to run the program for t cases.
For this, I have implemented a counting sort like algorithm (perhaps a bit naiive), that counts the number of occurrences of each number in the input. In case there are multiple numbers with the same maximum occurrence, I need to return the smaller among those. For this, I implemented sorting.
The issue I am facing is, that every time I run the program on Visual C++, I am getting an error that tells "vector subscript out of range". Under Netbeans, it is generating a return value of 1 and exiting. Please help me find the problem
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findmax(vector<int> a, int n)
{
int i,ret;
ret = 0;
for ( i = 0; i <n; i++)
{
if (a[i] > ret) {
ret = a[i];
}
}
return ret;
}
int main() {
int i = 0, j = 0, k = 0, n,m,r1,r2;
vector<int> a;
int t;
vector<int> buff;
cin>>t;
while(t--) {
cin>>n;
a.clear();
buff.clear();
for ( i = 0; i < n; i++) {
cin>>a[i];
}
sort(a.begin(),a.end());
m = findmax(a,n);
for ( j = 0; j < m+1; j++) {
buff[a[j]] = buff[a[j]] + 1;
}
k = findmax(buff,m+1);
for ( i = 0; i < m+1; i++) {
if (buff[i] == k) {
r1 = i;
r2 = buff[i];
break;
}
}
cout<<r1<<" "<<r2<<endl;
}
return 0;
}
After a.clear() the vector doesn't have any members, and its size is 0.
Add a call to a.resize(n) to make it the proper size. You also need to resize buff to whatever size it needs to be.
this line it's the culprit:
cin>>a[i];
you must use push_back:
cin >> temp;
a.push_back(temp);
or resize(n) before:
cin>>n;
a.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
then you should pass you vector by reference to findmax
int findmax(vector<int> &a, int n)
...
This isn't how you populate an array.
cin>>a[i];
You need to use the push_back() method or pre-allocate the appropriate size.
The problem is that you're illegally using indexes of your vector that don't exist (you never add any items to the vector). Since you know the size, you can resize it after you clear it:
a.clear();
a.resize(n);
buff.clear();
buff.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
will be out of range. The vector, as you construct it, has zero size.