Multidimensional array of struct - Segmentation fault - c++

I have a pointer to array of structure and when I try to initialize it, I get a segmentation fault.
MyStruct **** node = NULL;
node[0][0][0] = new MyStruct();
I tried to use 2D array and it Works fine.
What is wrong?
Thanks for your replies.

You need to allocate memory before using it. You can't just jump 3 levels without allocating and use it.
Allocate node first. Then you can access node[0].
Now if you allocate node[0], you can access node[0][0].
Go on like this.

Try to dynamically allocate the array first, using the new operator:
MyStruct ****node = new MyStruct***[MAX_SIZE];
for(int i=0; i<MAX_SIZE; ++i) node[i] = new MyStruct**[MAX_SIZE];
for(int i=0; i<MAX_SIZE; ++i)
for(int j=0; j<MAX_SIZE; ++j) node[i][j] = new MyStruct*[MAX_SIZE];
node[0][0][0] = new MyStruct();

Related

How to access 1 element in 2D dynamic array in C++

I'm new to C++, and I've been trying to figure out how to access just 1 element in a 2D array that I've dynamically allocated like so:
char** array;
array = new char*[3];
for(int i = 0; i < 3; i++) {
array[i] = new char [3];
}
I've been trying to access it like this:
cout<< array[0][0];
Whenever I try to do this, nothing prints out and the program segfaults.
How should I fix it so that it prints?
Thank you for your time!
If you're looking to create a 2D array you should take a look at this Stack Overflow post here. It has a nice image to explain how 2D memory is laid out and how to properly create the array. Remember, when you create dynamic memory using new you need to delete the memory manually with delete[]. The second response gives a code example of how to delete the 2D array. Once you have your array you can access it by cout << array[x][y], where x and y are your row and column indices. I'd focus on properly creating the 2D array and understanding that first.

Failed to allocate an array of pointers to a struct

I'm trying to allocate an array of pointers to a struct but there's something wrong with my code.
This is my struct:
struct Brick {
GameObject2D* handle_;
};
Brick** bricks_;
And this is how i'm trying to allocate memory for it:
int bricks_amount_ = 10;
bricks_ = (Brick**)malloc(sizeof(Brick*) * bricks_amount_);
The program crash. I've make a devenv on it to debug where's the problem and it crash on this line:
for (unsigned short int i = 0; i < bricks_amount_; i++){
bricks_[i]->handle_ = new GameObject2D(); <---------- CRASH!
}
Any suggestions?
PS: Sorry for my english :P
=========================================================================
[SOLUTION]
Finally i've decided to use std::vector instead raw pointers:
bricks_.resize(bricks_amount_);
but i've tried to make the malloc different way and it works too:
bricks_ = (struct Brick*)malloc(sizeof(struct Brick) * bricks_amount_);
or this:
bricks_ = new Brick[bricks_amount_];
Thank you to the people who wants to help!
It's C++:
don't use malloc, use new
don't use plain arrays, use std::vector or std::array
don't use raw pointers, use std::unique_ptr
Do not use
Bricks ** //will be a 2 dimensional array
Use instead
Bricks * //will be a 1 dimensioanal array
If you want a single dimensional array
Then do
`Bricks * bricks_ = (Bricks *)malloc(sizeof(Brick) * bricks_amount_ );
`
Then you can safely do without a crash
for (unsigned short int i = 0; i < bricks_amount_; i++){
bricks_[i]->handle_ = new GameObject2D(); <---------- There will not be CRASH!
}

Freeing memory between loop executions

Hi I'm coding a C++ program containing a loop consuming too much unnecessary memory, so much that the computer freezes before reaching the end...
Here is how this loop looks like:
float t = 0.20;
while(t<0.35){
CustomClass a(t);
a.runCalculations();
a.writeResultsInFile("results_" + t);
t += 0.001;
}
If relevant, the program is a physics simulation from which I want results for several values of an external parameter called t for temperature. It seems that the memory excess is due to not "freeing" the space taken by the instance of my class from one execution of the loop to the following, which I thought would be automatic if created without using pointers or the new instruction. I tried doing it with a destructor for the class but it didn't help. Could it be because the main memory use of my class is a 2d array defined with a new instruction in there?
Precision, it seems that the code above is not the problem (thanks for the ones pointing this out) so here is how I initiate my array (by the largest object in my CustomClass) in its constructor:
tab = new int*[h];
for(int i=0; i<h; i++) {
tab[i] = new int[v];
for(int j=0; j<v; j++) {
tab[i][j] = bitd(gen)*2-1; //initializing randomly the lattice
}
}
bitd(gen) is a random number generator outputing 1 or 0.
And also, another method of my CustomClass object doubles the size of the array in the following way:
int ** temp = new int*[h];
for(int i=0; i<h; i++) {
temp[i] = new int[v];
for(int j=0; j<v; j++) {
temp[i][j] = tab[i/2][j/2];
}
}
delete[] tab;
tab = temp;
Could there be that I should free the pointer temp?
You're leaking memory.
Could there be that I should free te pointer temp?
No. After you allocate the memory for the new array of double size and copy the contents, you should free the memory that tab is pointing to. Right now, you're only deleting the array of pointers with delete [] tab; but the memory that each of those pointers points to is lost. Run a loop and delete each one. Only then do tab = temp.
Better still, use standard containers that handle memory management for you so you can forget messing with raw pointers and focus on your real work instead.

copy matrix into where pointer points to in c++

How to copy a matrix into where a pointer points to?
I am new in c++. I tried a lot but I could not find any solution.
here is my code:
float *output = new float[HighRange];
output = new float[10 * 10];
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
output[j]=input[i][j]; ---> I have error in this line
Thanks in advance
There are several ways to arrange the elements of input in output. Here is one way:
output[i*10 + j] = input[i][j]
Aside from NPEs suggestion, you have a memory leak here:
float *output = new float[HighRange]; // allocate contiguous block HighRange * sizeof(float) bytes
output = new float[10 * 10]; // allocate contiguous block 100 * sizeof(float) bytes
Aside from this being unnecessary, you leak memory, i.e. you allocate storage in the first statement that you never free before assigning a new value to the pointer that hold the first address to the previously allocated storage.
When allocating memory dynamically using new, you need to make sure you delete it accordingly. For arrays, you need to do the following:
float *output = new float[HighRange]; // allocate
delete [] output; // deallocate, note the delete[] operator
output = new float[10 * 10]; // allocate anew
Note: This is just to display correct usage of new/delete[]. By no means do I suggest your code would be any better if you handled deallocation in your example. :)

Reallocating 2D arrays on C++

lets say i have:
#include <iostream>
using namespace std;
int **a; //Global Variable
int main()
{
n=5;
a = new int*[n];
for ( int i = 0 ; i < n ; i++ )
a[i] = new int[n] ;
}
is there any realloc() method to increase the row size? (column size is fixed)
I mean if the row size is 5 then i wanna make it 6 not much more, just +1.
I use
for(i=0;i<n;i++)
{
counter++;
a[i] = (int *) realloc(a[i],counter*sizeof(int));
}
but i think something is wrong....
Edit: please don't advise any vector or sth like that.. Cuz i need my array as global.
realloc only works when you allocated with malloc. If you used new, you'll have to delete and then use new again (or just use something like a std::vector).
EDIT: Since you asked for an example of how to use malloc:
a = new int*[n];
would become
a = (int **) malloc (n * sizeof (int *));
and
a[i] = new int[n] ;
would become
a[i] = (int *) malloc (n * sizeof (int));
You can write your own routine to resize the array.
If you want a resized block with size N
allocate (new) the new size N
copy old array/block to this newly allocated array/block
free the old array (delete)
To avoid calling this routine again and again, better preallocate a large chunk, the size of chunk will be determined by the need of your application, and should be such which avoid resizing the array a lot of times.
The answer is No!
C++ memory management does not contain functionality for reallocating/resizing allocated memory. You would have to implement such a thing yourself using new/copy/delete semantics