Declaring and initializing a global 2D array - c++

//gives the error expecting a declaration
int** my_array;
for (int i=0; i<200; i++)
{
my_array[i]= new int [200];
}
//initialize array with zeroes
for (int i = 0; i<200; i++)
{
for (int j = 0; j<200; j++)
{
my_array[i][j] =0;
}
}
In brief:
The 2D array is declared globally
It is initialized in the main. The main calls a function that saves 0's or 1's in specific cells of the array
The array is then printed by the main
Also advice whether the flow is correct?

If you want an array of an array of 200 bools, you could use std::array and std::bitset.
#include <bitset>
#include <array>
//...
std::array<200, std::bitset<200>> my_array;
Second, your code, even if you fix the syntax error is wrong. You would need to create my_array this way:
int** my_array;
//...
my_array = new int * [200];
for (int i = 0; i < 200; ++i )
my_array[i] = new int [200];
Then somewhere you have to delete this memory:
for (int i = 0; i < 200; ++i )
delete [] my_array[i];
delete [] my_array;
An alternate that creates a contiguous block and uses only two calls to new[]:
my_array = new int * [200];
int *pool = new int [200*200];
for (int i = 0; i < 200; ++i, pool += 200 )
my_array[i] = pool;
Then somewhere you have to delete this memory:
delete [] my_array[0];
delete [] my_array;
However I advise you use a container such as the std::array, std::bitset, std::vector, etc. instead of the int** approach.

Regarding your syntax error, it's probably due to something before the code you have shown.
The shown code,
int** my_array;
for (int i=0; i<200; i++)
{
my_array[i]= new int [200];
}
//initialize array with zeroes
for (int i = 0; i<200; i++)
{
for (int j = 0; j<200; j++)
{
my_array[i][j] =0;
}
}
compiles fine as the body of a function.
Regarding the logic, which is incorrect and which uses troublesome constructs,
do this:
auto my_array = vector<vector<bool>>( 200, vector<bool>( 200 ) );
where vector is std::vector from the <vector> header.
This avoids the raw pointers, the new-ing`, the loops, etc., all that you find problematic.
Alternatively you can declare it like this:
vector<vector<bool>> my_array( 200, vector<bool>( 200 ) );
Note that a global variable is usually troublesome, best avoided.

Related

C++ Variable-sized arrays using stdin and stdout

I'm trying to solve this problem on variable-sized arrays but I'm getting a compilation error. Not exactly sure where I went wrong.
Problem can be accessed in this PDF
My solution attempt is as follows:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q,size,elem,index,smallindex;
//input of n and q
cin>>n>>q;
//declare the array a
int* bigarr = new int[q];
//assign the individual arrays to each element of the array a
for (int i=0; i<n; ++i){
//input of size of the individual array
cin>>size;
int* smallarr = new int[size];
for (int j=0; j<size; ++j){
smallarr[j] = cin>>elem;
}
bigarr[i] = smallarr;
}
//obtain index queries
for (int k=0; k<n; ++k){
cin>>index;
cin>>smallindex;
cout<<bigarr[index][smallindex];
}
}
On this statement:
bigarr[i] = smallarr;
smallarr is an int* pointer, but bigarr is also an int*, ie an array of int, so bigarr[i] is a single int. You can't assign an int* pointer to an int value.
If you want bigarr to be an array of pointers to other arrays, you need to declare bigarr as int** instead of int*, and then use new int*[q] to allocate it.
int** bigarr = new int*[q];
Also, on this statement:
smallarr[j] = cin>>elem;
The expression cin>>elem returns an istream& reference to cin, it does not return the int value read into elem, like you are expecting. So you can't use the result of that expression directly in the assignment to smallarr[j]. You will have to read elem and assign it to smallarr in separate statements:
cin>>elem;
smallarr[j] = elem;
That said, note that your code is leaking all of the allocated arrays since there are no calls to delete[] anywhere. You need to add them:
int** bigarr = new int*[q];
...
for (int i=0; i<n; ++i){
...
int* smallarr = new int[size];
...
bigarr[i] = smallarr;
}
...
for (int i=0; i<n; ++i){
delete[] bigarr[i]; // <-- here
}
delete[] bigarr; // <-- here
Though, you really should be using std::vector instead of using new[]/delete[] manually at all (you already have #include <vector>):
std::vector<std::vector<int> > bigarr(q);
...
for (int i=0; i<n; ++i){
...
std::vector<int> smallarr(size);
for (int j=0; j<size; ++j){
...
smallarr[j] = elem;
}
bigarr[i] = smallarr;
/* alternatively:
bigarr[i].resize(size);
for (int j=0; j<size; ++j){
...
bigarr[i][j] = elem;
}
*/
}
I also see is that you are using q to allocate bigarr, but then you use n to loop through bigarr. You don't need two separate variables. Use either n or q for both tasks, and get rid of the other variable.
Unless you really intend to allocate more slots then you want to fill in. In which case, your outer loop needs to ensure that it doesn't exceed both n and q:
for (int i=0; (i<n) && (i<q); ++i){
Or:
for (int i=0; i<std::min(n,q); ++i){

How many different way exists to define 2D array with pointers in C++?

I try to define a 2D array with C++ with pointers and I don't know how can I define it true? I have some loops in the function and they are start with 1 to n and I want to allocate memory and at the end of function I want to delete allocated memory?
for define it like the following code. please help me to develop it.
int **W;
W = new int* [n];
for (int i=1; i <= n; i++)
W[i] = new int[n];
///////////////////////
for (int k=1;k<=n;k++)
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
do some thing!
///////////////////////
for ( int i = 1; i <= n; i++ )
delete [] W[i];
delete W;
For an array of size n, indices start from 0 - (n-1). Thus array[n] is out of bounds.
int **W;
int n = 3;
W = new int*[n];
for (int i = 0; i < n; i++)
W[i] = new int[n];
for (int i = 0; i < n; i++)
delete[] W[i];
delete W;
You have the general idea correct. But there are some errors in the details. C/C++ use 0-based indices to access arrays.
for (int i=1; i <= n; i++)
W[i] = new int[n];
needs to be
for (int i=0; i < n; i++)
W[i] = new int[n];
Similar changes need to be made in the other for statements.
Also, you need to delete W using the array delete operator. Instead of
delete W;
use
delete [] W;
Having said that, you should use std::vector instead of plain old dynamic arrays. With std::vector, you don't have to worry about deallocation of memory. The destructor of std::vector will take care of deallocating memory.
A 2D array of size n x n where each element is initialized to 0 can be defined simply as:
std::vector<std::vector<int>> array(n, std::vector<int>(n, 0));

declare and delete this version of a 2D array in c++

int *array[10];
for(int i = 0; i < 10; i++)
array[i] = new int[10];
//...
void passFunc(int *a[10]) //array containing pointers
{
//...
}
passFunc(array);
Im trying to figure out how to declare and delete this version of a 2D array. I started using int ** array, but in order to make one section of code easier, I need to switch to *[]. Can anyone help me out?
I have tried compiling my actual code (the above code is just an example), which looks like this:
int* filedata[LENGTH] = new int*[LENGTH]; //ERROR: array must be initialized with brace- enclosed identifiers.
EDIT:
Thanks!
Something like that
int** array = new int*[sizeX];
for(int i = 0; i < sizeX; ++i)
array[i] = new int[sizeY];
To delete
for(int i = 0; i < sizeX; ++i)
delete [] array[i];
delete [] array;
If I have understood correctly what you want then the allocation and deallocation will look as
int ** filedata = new int * [LENGTH];
for ( int i = 0; i < LENGTH; i++ ) filedata[i] = new int [LENGTH];
//...
for ( int i = 0; i < LENGTH; i++ ) delete [] filedata[i];
delete [] filedata;
Alternate version to the ones given:
int** array = new int*[sizeX];
int *pool = new int[sizeX * sizeY];
for(int i = 0; i < sizeX; ++i, pool += sizeY)
array[i] = pool;
To delete:
delete [] array[0];
delete [] array;
The advantage of using this is:
Only two calls to new[] and delete[] are required, regardless of the number of columns. In the previous answer, the number of calls to new and delete depend on the number of columns. This reduces fragmentation, and also will probably give you a speed increase if the number of columns is very large.
The data is contiguous. You can access any element in the 2d array from any other element using a simple offset.
The disadvantage is that the number of columns for each row needs to be the same, otherwise it becomes very difficult to maintain.

c++ deallocate 2d int array error

I get very frustrating error in following piece of code. Thats my array.
int **tab2 = new int*[3];
I allocate this like it.
for(i = 0; i < 10; i++) {
tab2[i] = new int[3];
tab2[i][0] = 40;
tab2[i][1] = 10;
tab2[i][2] = 100;
}
Then after using it i want to destroy it.
for(i = 0; i < 10; i++) {
delete [] tab2[i];
}
delete [] tab2;
And this causes core dump every single time. I tried many different ways to destroy it and every time get this error. What im making wrong here ?
This
int **tab2 = new int*[3];
does not do what you think it does.
You want an array that will contain TEN (10) pointers, each to an array of THREE ints.
new int*[3] is an array that contain THREE pointers.
What you want is this (live at coliru):
#include <iostream>
int main() {
int **tab2 = new int*[10];
for(int i = 0; i < 10; i++) {
tab2[i] = new int[3];
tab2[i][0] = 40;
tab2[i][1] = 10;
tab2[i][2] = 100;
}
for(int i = 0; i < 10; i++) {
delete [] tab2[i];
}
delete [] tab2;
}
With
int **tab2 = new int*[3];
you allocate an array of pointers of size 3. But than with
for(i = 0; i < 10; i++) {
tab2[i] = new int[3];
//...
}
you access it with up to index 9. That will surely go wrong.
The deletion process looks fine to me. To fix it, you should allocate an array of pointers with size 10instead of 3, e.g.
int **tab2 = new int*[10];
Looks like what you're trying to do is to create an N by M array, where N is known at runtime and M is fixed (in this case, 3).
Why not just do this?
{
std::array<int, 3> defaults = {{ 40, 10, 100 }};
std::vector<std::array<int, 3>> thing(10, defaults);
}
The vector, thing is automatically deallocated when it goes out of scope, and its size can be set at runtime. You still access the structure in the same way:
thing[1][2] = 3
Manual memory management can be easily avoided by using standard containers and smart pointers. Doing so will keep you code cleaner, and have fewer opportunities for dangling pointers and memory leaks.

Dynamic 2D Array Initialization

I want to create and initialize a 2D array but the initialization is failed. I encounter "The program has unexpectedly finished." in Qt Creator.
What is wrong?
in .h file
private:
int pop;
int d;
float **uye;
in .cpp file
pop=50;
d=12;
uye = new float*[pop];
for(int i=0; i<d; i++) uye[i] = new float[d];
for(int n=0; n<pop; n++)
{
for(int m=0; m<d; m++)
{
uye[n][m] = (float) n*m;
}
}
The first loop for(int i=0; i<d; i++) should probably be for(int i=0; i<pop; i++). Otherwise, you are only reserving space for 12 elements, but later try to access 50.
Note that having raw pointer members is considered a very bad idea in modern C++, because you need to worry about copying semantics. Better use a flat std::vector<float> and do the 2D to 1D mapping manually, or use a std::vector<std::vector<float> > with convenient access syntax.
I would prefer the second version. Without seeing more context:
pop = 50;
d = 12;
uye = std::vector<std::vector<float> >(pop, std::vector<float>(d));
The nested for loops that follow work exactly the same, no changes required.
What is wrong?
You're not using std::vector (that's one of the things that's wrong, #FredO covered the other thing).
#include <vector>
int main(){
typedef std::vector<float> inner_vec;
typedef std::vector<inner_vec> outer_vec;
int pop = 50, d = 12;
// first parameter to vector is its size
// second is what every element should be initialized to
outer_vec uye(pop, inner_vec(d));
for(unsigned n = 0; n < uye.size(); ++n){
for(unsigned m = 0; m < uye[n].size(); ++m){
uye[n][m] = (float)n*m;
}
}
}