Could anyone please explain me this piece of code? - c++

"header" is an object of a struct and you can consider header.img to have a value of 496. And header struct has 3 integer elements so is the value 12 bytes. (Considering 4 bytes a int)
double** MatrixBuffers = new double* [header.img];
MatrixBuffers[0] = new double[header.img* 12];
for (unsigned int i=1; i<header.img; ++i) {
MatrixBuffers[i] = MatrixBuffers[0] + i * 12;
}
globaldata.adv_MatrixBuffers = MatrixBuffers;
I understand that MatrixBuffers is a pointer to 496 doubles. But I don't understand what's happening in the second line.
MatrixBuffers[0] = new double[header.img* 12];
1.Does this mean MatrixBuffers[0] is a pointer to 496*12 doubles ?
2.What is happening in the for loop ?
3.Later in the code, MatrixBuffer[0] is being passed to a function. Does this mean I am passing a pointer that is the base address to MatrixBuffers[0] ?

For a double pointer you have to allocate memory for first as well as second dimension.
For the second level instead of allocating memory for every dimension he allocates memory at one shot
MatrixBuffers[0] = new double[header.img* 12];
Inside the for loop they move the address and assign the same to every index.
Instead he can also do like this inside the for loop and comment the line above the for loop
MatrixBuffers[i] = new double[header.img];

Related

How to Use Malloc on a 2D Array and Not Overwrite Previous Values in C++

I am trying to use malloc to allocate the inner section of a dynamically allocated 2D array. I know that vectors and new are better but I am required to use malloc and realloc. I start off with two variables.
buffer_count = 0
buffer_size = 3
I then create the 2D array of size [3][26](each inner array just has to be of size 26).
Here is that creation:
int ** array_creation (){
int ** arr = (int **) malloc(buffer_size * sizeof(int *));
for(int i=0;i<buffer_size;i++){
arr[i] = (int *)malloc(26 * sizeof(int));
}
}
Every time I add to the next array location I increase the buffer_count. When the count is equal to the size, I am trying to double the size of the outer part of the array.
if(buffer_count >= buffer_size){
buffer_size = buffer_size * 2;
arr = (int **) realloc(*arr, buffer_size *sizeof(int));
for(int i=0;i<buffer_size;i++){
arr[i] = (int *)malloc(26 * sizeof(int));
}
This code above will run but it will obviously write over the first 3 since I am using malloc in the inner for loop.
Any attempt at only adding from say buffer_count / 2 and so on and make the inner for loop arr[I] be something like arr[buffer_size/2] to start from the end of what was already allocated to not overwrite it I get a Segmentation Error. I have also tried doing something like:
if(arr[i] == NULL){
//write to array
}
That also does not work. Like I said, I know the draw backs of using malloc in C++ but I am required to here. Thank you

Error on Multiple Array Dynamic Memory Allocation

please advise why below do not work. use VC2017:
long **l;
l = new long [5][7];
it shows error as:
"a value of type "long*[7]" can not be assigned an entity of
long**"...
How can I solve it?
You need to declare and init the first array of pointer to long* and then assign to each his own array as:
long** l = new long*[5]; // declare array of pointer of 5 cell
for(int i = 0; i < 5; ++i)
l[i] = new long[7]; // assign to each cell array with 7 cells
Remember that anything allocated with new is created on the heap and must be de-allocated with delete.

How to make a copy of a byte array in c code?

I have the address of the first char in my byte array, and it's size:
const char *rawImageBytes, int size
And I want to copy the content to a different byte array. and then modify that one a bit.
This is whay I am doing now:
LOGI("FrameReceived will reach here 1");
modifiedRawImageBytes = rawImageBytes;
jint sizeWH = width * height;
jint quarter = sizeWH/4;
jint v0 = sizeWH + quarter;
for (int u = sizeWH, v = v0, o = sizeWH; u < v0; u++, v++, o += 2) {
modifiedRawImageBytes[o] = rawImageBytes[v]; // For NV21, V first
modifiedRawImageBytes[o + 1] = rawImageBytes[u]; // For NV21, U second
}
But I don't get the correct colours, as if I would to this in Java, instead of c++.
And I am assuming this happens, because I just do modifiedRawImageBytes = rawImageBytes; instead of actually copying the whole byte array, so that it can start in memory from another address pointer.
A bit of a beginner with c, so I'm lost at this, can someone help me understand what is done wrong?
PS: I am assuming that, because even if I send the rawImageBytes and not the modifiedRawImageBytes, it will still be modified
This is because const char * is a pointer. This mean it represent an address. So you guessed right, the new variable represent the same datas.
To avoid this you should create a copy.
char modifiedRawImageBytes[size];
//if the pointer come from function's param don't redeclare it ;)
std::memcpy(modifiedRawImageBytes, rawImageBytes, size*sizeof(char));
This code will allocate a new char array and then memcpy will copy in the previous array data in the new array.
Note that you need to includecstdio

Undetected error with new operator

I was messing around trying to understand pointers and the operator "new"
and I ended up getting even more confused on what these 2 codes should result to, which is other but its not, so I wanted to understand what happened here.
thanks in advance.
#include <iostream>
using namespace std;
int main()
{
int * p = new int(50);
p[1] = 33;
cout << *p << endl;
}
Output: 50
and when I tried this
#include <iostream>
using namespace std;
int main()
{
int * p = new int[50];
p[1] = 33;
cout << *p << endl;
}
Output: -842150451
I was wondering about the meaning of each result.
In the first case
int * p = new int(50); // allocates 1 int on heap, initialized to value of 50
p[ 1] = 33; // p gives you the address of integer,
// p[1] moves the p pointer forward and accessing
// the pointed object results in undefined behavior,
// this means that at this moment anything can happen
// exception, crash, home war, nothing, everything,
// printing garbage value as well
In the second case:
int* p = new int[50]; // allocates 50 ints on heap, uninitialized
p[ 1] = 17; // initializes element with index 1 to value of 17
std::cout << *p; // p gives you the address of first element, with index 0
// which is still uninitialized, thus prints garbages
You should use
int* p = new int[50]();
to value-initialize ints to 0.
In the first one, you created dynamically a single int with a value of 50. When you try to assign the value 33, you actually assign it in memory that is not yours. It is undefined behaviour. But when you print it, you print the original value you made, which was 50.
In the second one, you created dynamically an array of 50 int. You've then specified the second value of in the array should be 33.* So when you print the value with cout << *p << endl;, you end up printing only the first value, which is undefined. Try it again, you'll probably get another value.
*Edit: as pointed in the comments, I should have been more explicit about this. An array starts at 0. So if you want to access the first value p[0] would do it.
In the first case you're creating an array of 50 ints, assigning a value to the SECOND int in the array, and then printing the first element in the array. Array indices start at 0, so when you dereference the pointer in your cout statement, it's printing whatever happened to be in memory at index 0.
In the second case you're creating a single integer, and initializing it with the value 50. When you dereference the pointer in the print statement, you're getting the integer you just created. The p[1] = 33 may or may not cause an error as your accessing unassigned memory.
int* p = new int[50];
allocates an array of int on the heap with 50 uninitialized elements, ranging from index 0 to 49.
Setting p[1] to 33 doesn't change p[0] which is what you're printing with "cout << *p".
The value -842150451 (0xCDCDCDCD in hex) is a magic number "Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory", see this question on SO.
int* p = new int(50);
allocates exactly one int on the heap and initializes it with the value 50, so setting p[1] afterwards should result in undefined behavior since you didn't allocate that memory where p[1] is referring to.
I'd recommend to use the Visual Studio Memory Windows to see what happens to the memory you're allocating while stepping through your code.

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