C++ replacing values in a dynamic 2D Array - c++

I'm trying to replace the '.' in my array with 'O'but it inserts it in between rather than taking its place. Please help I don't know what I'm doing wrong.
#include <iostream>
using namespace std;
char** createField(int w, int l)
{
int obstacles;
char ** arr = new char * [w];
for(int i=0; i<w; i++)
{
arr[i] = new char[l];
}
//Initializing the values
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
arr[i][j] = 0;
}
}
cout<<"Enter number of obstacles: ";
cin>>obstacles;
int x=0;
int y=0;
for (int j = 0; j < obstacles; ++j) {
cout<<"Enter location of obstacles: ";
cin>>x>>y;
arr[x][y] ='O';
}
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
if(i==0 || i == w-1){
cout<< arr[i][j]<< 'W';
}else if(j==0 || j==l-1){
cout<< arr[i][j]<< 'W';
} else
cout<< arr[i][j]<< '.';
}
cout<<"\n";
}
return arr;
}
int main() {
int w;
int l;
cout << "Enter the Width: ";
cin >> w;
cout << "Enter the length: ";
cin >> l;
//Pointer returned is stores in p
char **p = createField(w, l);
//Do not Forget to delete the memory allocated.It can cause a memory leak.
for (int del = 0; del < w; del++) {
delete[] p[del];
}
delete[]p;
}
Here is an example of my output, I want the 'O' to replace the '.' rather than be in between the two. Also if someone could explain why this is happening that would be really helpful Thanks.
Example of output: w.O.w
Desired output: w.Ow

When you set arr[i][j] = 0, it will cast 0 into char before assigning it to arr[i][j]. 0 casts to the literal '\0' which means a null character. Later when you print the contents of arr, the null characters cannot be seen in output which is part of the underlying cause of your confusion. Hope that explains what's going on a little bit better.

Related

Segmentation Fault in dynamically array creation

I was making a cpp program in which it takes two input from the user which determine the size of the 2d array and pass the values to the mat class constructor and dynamically create an array of the user's defined size. But, I don't know why it is not working and showing segmentation fault
#include<iostream>
using namespace std;
class mat{
int **a;
int r, c;
public:
mat(int row, int col){
r = row;
c = col;
for(int i = 0; i < r; i++){
*a = new int[r];
*a++;
}
}
void input(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cin >> a[i][j];
}
}
}
void display(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};
int main()
{
int r, c;
cout << "enter row :";
cin >> r;
cout << "enter column :";
cin >> c;
mat m(r, c);
m.input();
cout << "array \n";
m.display();
}
I can feel that the issue is with the for loop in the constructor or maybe I am doing it wrong.
The class contains several errors.
The variable a is never initialized. When we try to address the memory pointed to by a we get a segmentation fault. We can initialize it like this a = new int*[r]
We should not change where a point's to, so don't use a++. Otherwise a[i][j] will not refer to the i'th row and the j'th column. We would also want to release the memory at some point.
The inner loop for the columns for(int j = 0; i < c; j++) once entered will never terminate and will eventually produce a segmentation fault. We need to change i < c to j < c.
If we fix these errors, it looks like this:
class mat {
int** a;
int r, c;
public:
mat(int row, int col) {
r = row;
c = col;
a = new int*[r];
for (int i = 0; i < r; i++) {
a[i] = new int[c];
}
}
void input() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> a[i][j];
}
}
}
void display() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};

Why the output is not showing?

My program is to find the smallest positive number missing from an array. With the following input I expect an output of 2.
6
0
-9
1
3
-4
5
My problem is that it does not give any output. Can anyone explain this please?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int array[n];
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
int const N = 1e4+2;
bool indexarray[N];
for (int i = 0; i < N; i++)
{
indexarray[i] = false;
}
for (int i = 0; i < n; i++)
{
if (array[i] > 0)
{
indexarray[array[i]] = true;
}
}
int ans = -1;
for (int i = 1; i < N; i++)
{
if (indexarray[i] == false)
{
ans = i;
}
}
cout << ans << endl;
return 0;
}
I think because int array[n]; makes an array called array with n elements in it, with the first one starting at array[0].
cin >> array[n]; needs to modify array[n], but because the first element is array[0], the last element is array[n-1], and array[n] does not exist. Your code gave an error and exited.
Try changing
for (int i = 0; i < n; i++)
{
cin >> array[n];
}
to
for (int i = 0; i < n; i++)
{
cin >> array[i];
}
Also, I think variable length arrays are non-standard, so maybe try changing that. Replace it with std::vector<int> array(n) should work.

Heap corruption detected error in C++

Here is my code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main() {
int** arr=NULL;
int num=0;
cin >> num;
int* big=NULL;
arr = new int*[num];
for (int i = 0; i < num; i++) {
arr[i] = new int[5];
}
big = new int[num];
for (int i = 0; i < num; i++) {
for (int j = 0; j < 5; j++) {
while (1) {
cin >> arr[i][j];
if (arr[i][j] >= 0 && arr[i][j] < 100)
break;
}
}
}
for (int i = 0; i < 5; i++) {
big[i] = 0;
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < 5; j++) {
if (big[i] < arr[i][j]) {
big[i] = arr[i][j];
}
}
}
for (int i = 0; i < num; i++) {
cout << "Case #" << i + 1 << ": " << big[i] << endl;
}
delete[]big;
for (int i = num-1; i>=0; i--) {
delete[]arr[i];
}
delete[]arr;
return 0;
}
When I run this code, it says that there are heap corruption error (heap corruption detected). I think it means that there are some errors at 'new' or 'delete' parts in my codes, but I cannot find them. I hope someone to answer. Thanks.
Error is here:
big = new int[num];
...
for (int i = 0; i < 5; i++) {
big[i] = 0;
}
So when you have num less than 5 you are writing outside the array.
Anyway you are using C++ so use vector for such tasks.
#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
int main() {
vector<vector<int>> arr;
int num=0;
cin >> num;
arr.resize(num, vector<int>(5));
for (auto &row : arr) {
for (auto &cell : row) {
while (1) {
cin >> cell ;
if (cell >= 0 && cell < 100)
break;
}
}
}
vector<int> big(arr.size());
for (int i = 0; i < arr.size(); i++) {
for (auto &cell : arr[i]) {
if (big[i] < cell) {
big[i] = cell;
}
}
}
for (int i = 0; i < num; i++) {
cout << "Case #" << i + 1 << ": " << big[i] << endl;
}
return 0;
}
In many places in your code, you're indexing your big array using indexes from 0 to 5, while the array is allocated using user input, if user input was 4 for example, your code is undefined behavior.
If you're using c++, you shouldn't be manually allocating the arrays, use std::vector instead, it will take care of managing memory for you, so you don't have to new and delete memory yourself.
With std::vector, your code would look somewhat like this.
std::vector<std::vector<int>> arr;
std::vector<int> big;
cin>>num;
arr.resize(num, std::vector<int>(5));
big.resize(5);
You will also be able to use at method to access elements while bound-checking, and size method to get the number of elements of the array.

Scanning char array and putting it in struct properly in c++

Wanted to get my char array to be in a struct, but it crashes.
As I realised after, there is also a problem when scanning the array.
The input string consists of two words, name and surname, separated by a space. I haven't yet written the part where it scans the second word, so now it scans only the first.
The check lines in code have s weird output. I input "James" and it gives me "J8224a8224m8224e8224s8224" and then crashes.
#include <iostream>
#include<string.h>
using namespace std;
struct base
{
char* name;
char* surname;
int point1;
int point2;
};
main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base a[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i < n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k < j; k++) //check
cout << sym[k] << ' '; //check
strcpy(sym, a[i].name);
j = 0;
}
}
There are several errors:
You cannot use static initialization for base a[n], because variable n is not known while compiling.
You have to initialize a[i].name before you do strcpy.
You shlould use sptncpy instead of strcpy if you know lenght which is j.
You code should look like this
int main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base *a = new base[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i<n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k<j; k++) //check
cout << sym[k] << ' '; //check
a[i].name = new char[j];
strncpy(sym, a[i].name, j);
j = 0;
}
}

Segmentation Fault In Probability Calculator

I'm compiling this on linux. It will compile and run, but when I enter values for n and p, this is what my terminal looks like:
7
1.0
Segmentation fault (core dumped)
In this case, 7 is the input for n, and 1.0 is the input for p. I've tried this with different values. The idea is to use Dynamic Programming to fill in a 2D array of probabilities through recursion. Let me know if you need more info, but this is the entirety of the code.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int n;
double p;
cin >> n;
cin >> p;
cout << n;
cout << p;
cout << "Initializing array.";
double** probability = new double*[n];
for(int i = 0; i < n; ++i)
{
probability[i] = new double[n];
}
//cout << "Beginning filling i loop.";
for(int i = 0; i < n; i++)
{
probability[i][0] = 0;
}
//cout << "Beginning filling j loop.";
for(int j = 0; j < n; j++)
{
probability[0][j] = 1;
}
//cout << "Beginning filling nested loop.";
for(int i = 1; i< n; i++)
{
for(int j = 1; j< n; j++)
{
probability[i][j] = (p * probability[i-1][j]) + ((1-p) * probability[i][j-1]);
}
}
cout << "Probability: ";
cout << probability[n][n];
//cleanup
for(int i = 0; i < n; ++i)
{
delete probability[i] ;
}
delete probability;
return 0;
}
cout << probability[n][n];
probability[][] is an n by n array. The last element is probability[n-1][n-1] , so you are running off the end of the array and invoking undefined behavior.