0

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

JBL
  • 12,588
  • 4
  • 53
  • 84
user3641098
  • 23
  • 1
  • 5
  • 7
    This is C++. Why is `output` not a `std::vector` at least? – chris Sep 19 '13 at 15:30
  • Is the first line suppose to be your `input`? If not, you have a memory leak since you are setting `output` to 2 dynamically created memory blocks without freeing the first. – Zac Howland Sep 19 '13 at 15:33
  • What error do you get? – thokra Sep 19 '13 at 15:36
  • Use a [wrapper around a vector](http://stackoverflow.com/a/2216055/179910), for both `input` and `output`, which will allow you to just do `output = input;`. – Jerry Coffin Sep 19 '13 at 15:48
  • @JerryCoffin: Although agreeable in general, I think the problem is much more basic than that. After all, the expression in question is legal if `input` actually is a 2D-array. Knowing what the compiler complains about would be very helpful ... – thokra Sep 19 '13 at 15:56

2 Answers2

1

There are several ways to arrange the elements of input in output. Here is one way:

output[i*10 + j] = input[i][j]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

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. :)

thokra
  • 2,874
  • 18
  • 25