i am new to programing and i am trying to understand the two dimensional array. i wrote this code to just test my code to see if it working or not. unfortunately, i am getting a segmentation error. i know that means that something i wrote is unreadable for the compiler but i do not know what is it. because everything seems fine to me.
#include<iostream>
using namespace std;
int main(){
int col, row,i;
int **array;
cout << "How many rows?\n";
cin >> row;
cout << "How many colomns\n";
cin >> col;
cout << "!!!!!!!!!!!!";
array = new int*[row];
for (int i = 0;i<row;i++){
array[i] = new int[col];
}
cout << "!!!!!!!!!!!!";
for( i=0; i<row; i++){
int x=1;
array[0][i]= x;;
x++;
}
cout << "!!!!!!!!!!!!";
cout << array[row][col];
for(i=0; i<row; i++){
delete [] array[i];
delete [] array;
}
return 0;
}
the ERROR is:
"
How many rows?
3
How many colomns
3
Segmentation fault (core dumped)
"
array[0][i]= x; looks wrong. It should be:
array[i][0]= x;
First index is for row and second for col.
Later cout << array[row][col]; is also wring as row is out of range.
The way you delete the array is also wrong, it should be:
for(i=row - 1; i >= 0; --i){
delete [] array[i];
}
delete [] array;
cout << array[row][col];
Out of range in each of the two dimensions, as others have said.
for(i=0; i<row; i++){
delete [] array[i];
delete [] array;
}
You're deleting array's elements three times, once for each element. This is good. You're also deleting array itself three times. This is dangerous and wrong.
so it should be like this?
#include<iostream>
using namespace std;
int main(){
int col, row,i;
int **array;
cout << "How many rows?\n";
cin >> row;
cout << "How many colomns\n";
cin >> col;
array = new int*[row];
for (int i = 0;i<row;i++){
array[i] = new int[col];
}
cout << "!!!!!!!!!!!!";
for( i=0; i<row; i++){
int x=1;
array[i][0]= x;;
x++;
}
cout << "!!!!!!!!!!!!";
for(i=0; i<row; i++){
for(int j=0; j<col; j++){
array[i][j];
}
}
cout << array[row][col];
for(i=0; i<row; i++){
delete [] array[i];
delete [] array;
}
return 0;
}
This line is out of range cout << array[row][col];.If you want to print the last element then change this line to cout << array[row-1][col-1];
As others mentioned the below is code for deleting the allocated memory
for(i=0; i <row; i++){
delete [] array[i];
}
delete [] array;
Also in your code below x is always going to be 1 , x++ is noneffective.
for( i=0; i<row; i++){
int x=1;
array[0][i]= x;
x++;
}
if you want to increment x for each row then initialize x outside the loop
like this
int x=1;
for( i=0; i<row; i++){
array[0][i]= x;;
x++;
}
Related
I'm trying to generate and solve an NxN odd-numbered magic square through dynamic memory allocation but whenever I run the code, it displays nothing on the terminal and the programme ends. I reckon it has something to do with the dynamic allocation of the 2D array, as when I make a normal NxN array with a constant size, the programme runs fine. I'd appreciate any help regarding this!
#include<bits/stdc++.h>
#include<cmath>
using namespace std;
void calcuateMagicSquare(int N)
{
int **Array;
Array=new int*[N];
for(int i=0; i<N; i++)
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
int nSquare=N*N;
int i=N/2;
int j=N-1;
for(int k=1; k<=nSquare;)
{
if(i==-1 && j==N)
{
j=N-2;
i=0;
}
else
{
if(j==N)
{
j=0;
}
if(i<0)
{
i=N-1;
}
}
if(Array[i][j])
{
j=j-2;
i++;
continue;
}
else
{
Array[i][j]=k++;
}
j++;
i--;
}
int SolutionMagicSquare=N*(N*N+1)/2;
cout << "Solution of the magic Square: " << SolutionMagicSquare << endl;
cout << "MAGIC SQUARE: \n" << endl;
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
cout << setw(4) << Array[i][j] << " ";
cout << endl;
}
}
}
int main()
{
int N;
cout << "Please enter the dimension of the magic square:" << endl;
cin >> N;
calcuateMagicSquare(N);
}
This isn't too bad.
int ** Array=new int*[N];
for(int i=0; i<N; i++)
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
The memset is causing your trouble, and it's wrong for two reasons. First, let's say you really wanted to do that. You don't, but let's say you did. How big is sizeof(Array). Array is an int **. On a 64-bit machine, that's 8 bytes. So conveniently, you only destroyed the first pointer.
What you really need to do is this:
int ** Array=new int*[N];
// Don't do this memset, but showing you what it should look like)
memset(Array, 0, sizeof(int *) * N);
for(int i=0; i<N; i++)
{
Array[i]=new int[N];
// But this one is safe
memset(Array[i], 0, sizeof(int) * N);
}
Your version was erasing the first pointer -- Array[0]. I put that first memset in there so you could see what it would look like if you needed it. It's the second one you need. You're clearing out the size of an int times the number of ints that you have.
I'm trying to write code to enter 'n' Number of sentences and store it in an array. My for loop quits on the 4th iteration ? Can anyone help me?
int main(){
cout<<"Enter the number of sentences: ";
int n;
cin>>n;
cin.ignore();
char *array[50];
int br;
for (int i = 0; i<n; i++)
{
char* sentence = new char();
cout<<"Enter "<<i+1<<" sentence: ";
cin.getline(sentence,50);
br=0;
while(*sentence != '\0')
{
br++;
sentence++;
}
sentence=sentence-br;
for(int j=0; j<br; j++)
{
array[i][j] = sentence[j];
}
delete sentence;
}
for(int i=0; i<n;i++)
{
cout<<array[i]<<endl;
}
delete[] array;
return 0;
}
char* sentence = new char();
cout<<"Enter "<<i+1<<" sentence: ";
cin.getline(sentence,50);
This only allocates space for a single char, but you attempt to write up to 50 chars into that memory. Accessing memory that you don't own causes your program's behavior to be undefined.
for(int j=0; j<br; j++)
{
array[i][j] = sentence[j];
}
This attempts to copy the first br characters from sentence to array[i], but array is full of uninitialized pointers. Dereferencing an uninitialized pointer results in undefined behavior and then attempting to write to the memory it's "pointing" to is more undefined behavior.
delete[] array;
At the end of your program you attempt to release the memory allocated for array, but you did not allocate that memory via new. Once again, undefined behavior. array has automatic storage duration so its memory will be automatically released when it goes out of scope; you must not attempt to release it with delete.
Instead of a mix of static arrays and dynamic memory management, you should use a std::vector<std::string> instead. This will do all of the memory management for you:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::cout << "Enter the number of sentences: ";
int n;
std::cin >> n;
std::cin.ignore();
std::vector<std::string> array(n);
for (int i = 0; i < n; i++) {
std::cout << "Enter " << i + 1 << " sentence: ";
std::getline(std::cin, array[i]);
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << std::endl;
}
}
Thank on proposal, but I'm not allowed to use string or cstring library, I've tried to code from scratch and I think I got it.
int main(){
cout<<"Enter the number of sentences: ";
int n;
cin>>n;
cin.ignore();
char** array = new char*[n];
for (int i = 0; i<n; i++)
{
cout<<"Enter "<<i+1<<" sentence: ";
array[i] = new char[50];
cin.getline(array[i],50);
}
for(int i=0; i<n;i++)
{
cout<<array[i]<<endl;
}
for(int i = 0; i<n; i++)
{
delete [] array[i];
}
delete [] array;
return 0;
}
Have I allocated and deallocated memory right?
hope you doing well.
so i have just started to do an assignment and the first thing i wanted to do was to create the two dynamic array. however, there is something wrong with the array i can't assign values to it. Here is the code:
void Room::memory(int **array){
int x,x2;
int count=0;
cout << "Array size? rows: columns: \n";
cin >> x >> x2;
array = new int*[x];
for(int i=0; i<x;i++){
array[i]= new int[x2];
}
for(int i=0; i<x; i++){
for(int j=0; j<x2; j++){
array[i][j]=count;
count++;
}
}
for(int i=0; i<x;i++){
array[i]= new int[x2];
}
for(int i=0; i<x; i++){
for(int j=0; j<x2; j++){
cout<< array[i][j]<< " | ";
}
cout << endl;
}
}
i always get the value 0 for my array. whether i use this line or not:
array[i][j]=count;
i tied to compare my code with someone else and it is the same steps but it doesn't work for me.
class Room{
private:
int **array;
public:
void memory(int **array);
};
Why do you do
for(int i=0; i<x;i++){
array[i]= new int[x2];
} twice?
at the same time, please change void memory(int **array); to void memory();
while you crested the 2nd 2D dynamic array,you did not initialize it...And just printed it... In the 2nd 2D array you also need to initialize before printing the all index values....
for(int i=0; i<x;i++){
array[i]= new int[x2];
}
//here should be the initialization
for(int i=0; i<x; i++){
for(int j=0; j<x2; j++){
cout<< array[i][j]<< " | ";
}
cout << endl;
}
I am learning C++ by myself,by solving different problems.
I am trying to solve problem which was originally designed for Pascal in C++.
It should ask user to input 3 integers M,N and q.
Then it should make 2d array of integers with size MxN, where all the elements of (I=I,...M) line will be the members of geometrical progression with first element equal to number of line (I) and denominator q.
I wanted to create a dynamic massive, but I realized that it won't really work with two undefined integers. So, I tried vectors. I guess that I created them in a right way, but I've got no idea how to make a geometrical progression.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int m, n, q;
cout << "Enter the number for M \n";
cin >> m;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for N \n";
cin >> n;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for Q \n";
cin >> q;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
int** matrix;
matrix = new int*[m];
for (int i = 0; i < m; i++)
matrix[i] = new int[n];
for (int i = 0; i < m; i++)
{
matrix[i][0] = i + 1;
}
for (int i = 0; i < m; i++)
{
for (int j = 1; j < n; j++)
{
matrix[i][j] = (i + 1)*pow(i, j);
cout << matrix[i][j];
}
}
system("pause");
return 0;
}
Note: You can create a two dimensional array of a variable size, although it involves memory allocation and is slightly ugly.
int** matrix;
matrix = new int*[M];
for (int i = 0; i < M; i++)
matrix[i] = new int[N];
That's the code to create an array of size MxN.
Don't forget to deallocate your memory like so:
for (int i = 0; i < M; i++)
delete matrix[i];
delete matrix;
As far as your question about the geometric progression, I am unsure of what you are asking. When you say geometric progression do you refer to something along the lines of 2 10 50 250 etc.? I am not sure what you mean by "lines" as you don't refer to any such variable in your code.
EDIT
So once the MxN matrix is created, iterate through the rows and initialize the rows like so:
for (int i = 0; i < M; i++)
{
matrix[i][0] = i+1;
}
This should set the first column of each row to the correct number.
Then something along the lines of this should fill out the rest of the geometric progression:
for (int i = 0; i < M; i++)
{
for (int j = 1; j < N; j++)
{
matrix[i][j] = (i+1)*pow(r,j);
//note that you'll probably have to do some typecasting
//p.s. I'm not 100% sure that this is the correct formula
}
}
I think this is what you are looking for. Let me know if it works because I haven't tested it myself.
Print the matrix like this:
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
I'm trying to create a 3D char array with dynamic memory. I create the char*** point in main then pass it to input and everything works fine until the input function returns and i try to repring the same locaton from main. I get "Access violation reading location." Any suggestions?
void input(char ***a, int f, int n)
{
cin >> f;
cin >> n;
a = new char**[f];
for (int i =0; i <f; ++i)
{
a[i]= new char*[n];
for (int j=0; j <n; ++j)
{
a[i][j] = new char[n];
}
}
for (int i =0; i<f; ++i)
{
for (int j=0; j<n; ++j)
{
for (int k = 0; k <n ;++k)
{
a[i][j][k] = '.';
cout << a[i][j][k];}
}
}
cout <<endl << endl<< a[2][5][5]; //test to see is value is '."
}
int main()
{
char ***station = 0;
int floors=0, n=0;
input(station, floors, n);
cout << endl << endl << station[2][5][5];
}