0

I have

main(){...
float **tree;   
//How to set some values here for e.g. If I want tree to be a 15x2 array of some values?
reprVectorsTree *r1 = new reprVectorsTree(tree,8,2);
...}

reprVectorsTree(float **tree, int noOfReprVectors, int dimensions)
{.....

How to use malloc here so that I can set some data inside the tree array?

2
  • Just like your old question, you should tag this properly as C++. Commented Aug 16, 2012 at 10:19
  • You use new in the code but ask for usage of malloc. What exactly do you mean? Commented Aug 16, 2012 at 10:51

2 Answers 2

1

To allocate memory for tree, try something like:

float** tree;
tree = (float**)malloc(15 * sizeof(float*));
for(i = 0; i < 15; i++) 
    tree[i] = (float*)malloc(2 * sizeof(float));

Now you can set values:

for(i = 0; i < 15; i++)
    for(j = 0; j < 2; j++)
        tree[i][j] = 2;

Don't forget to free it later, although I don't understand why you are combining new and malloc together?

Sign up to request clarification or add additional context in comments.

Comments

0

I guess it's the tree variable you want to allocate for.

You can do like this:

float **tree;

// Allocate 15 "arrays"
tree = new float*[15];

for (int i = 0; i < 15; i++)
{
    // Allocate a new "array" of two floats
    tree[i] = new float[2];

    // Fill the newly allocated floats with "random" data
    tree[i][0] = 1.0;
    tree[i][1] = 2.0;
}

However, if it's possible I would recommend that you change the reprVectorsTree object to accept std::vector< std::vector< float > > instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.