Reputation: 375
I am completely stuck on this problem... The code structure that is given is as follows:
typedef struct _myvar{
uint32_t someInt;
uint32_t *ptr;
} myvar;
...
myvar **var;
..
var = new myvar*[x]; // where x is an int
for(int i = 0; i < y; i++){ // y is usually 2 or 4
var[i] = new myvar[z]; //create dynamic 2d array
for(int j = 0; j < z; j++){
var[i][j].ptr = new int[b]; //where b is another int
}
}
What happens is I want to create a 2d structure that has one part of it being 3d i.e. the ptr is just a pointer to an array of ints.
My code compiles but I get seg faults in trying to allocate memory so ptr can point to it. I tried working on this for about an hour and figure it was time for some help.
Thanks!
EDIT1: Fixed code issue in regards to comment on code not compiling.. Secondly... I cannot use vectors as much as I would like to... The data structure that I have there is what I have to use.
EDIT2: b is dynamic and set at the command line. For testing purposes use 16.
Upvotes: 0
Views: 74
Reputation: 5706
I think you are getting confused with your indices. In your first loop you use var[i], so i must stop at x, not at y. For the columns I have used j and y. Not sure what z is. Then, as pointed out by others, you shouldn't mix int and uint32_t. Try this:
#include <iostream>
using namespace std;
typedef struct _myvar{
uint32_t someInt;
uint32_t *ptr;
} myvar;
int main() {
myvar **var;
int x = 3;
int y = 4;
var = new myvar*[x]; // where x is an int
for(int i = 0; i < x; i++) { // i stops at x
var[i] = new myvar[y]; //create dynamic 2d array
for(int j = 0; j < y; j++){
var[i][j].ptr = new uint32_t[16]; // used 16 for testing
}
}
return 0;
}
Upvotes: 1