user3641098
user3641098

Reputation: 23

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

Upvotes: 0

Views: 112

Answers (2)

thokra
thokra

Reputation: 2904

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

Upvotes: 0

NPE
NPE

Reputation: 500943

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

output[i*10 + j] = input[i][j]

Upvotes: 1

Related Questions