Two dimensional array, what does *(pointerArray[i] + j)? - c++

i just got this task of finding out how this code works.
int array[rows][coloums];
int *pointerArray[rows];
for (int i = 0; i < rows; i++) {
pointerArray[i] = array[i];
for (int j = 0; j < coloums; j++) {
*(pointerArray[i] + j) = 0;
}
}
The thing I'm courious about is the *(pointerArray[i] + j), I think it's the same thing as pointerArray[i][j], since you can access the element both ways, But can anyone tell me what is actually happening with the *()? Like how does the compiler know that im asking for the same as pointerArray[i][j]?
Thanks for the answers!

When you do pointerArray[i] + j, you request the element pointerArray[i], which is a int*, and increment that pointer by j (also returning an int*). The *(...) simply dereferences the pointer and returns the int at that position. * is called the dereference operator (in this case). So yes, it's equivalent to pointerArray[i][j].

In this context, the * operator is the dereference operator. The value it prepends will be the location in memory at which it will return a value.
The parenthesis are grouping an addition operation so that the compiler knows that the result of this addition will be used for the dereference. It's simply a case of order-of-operations.
Keep in mind that the [] operator does the same thing as the dereference operator, because arrays are essentially a kind of pointer variable. If you imagine a two-dimensional array as a 2D grid of values with rows and columns, in memory the data is laid out such that each row is strung one after the next in sequential order. The first index in the array (i) along with the type of the array (int) tells the compiler at what offset to look for the first location in the row. The second index in the array (j) tells it at what offset within that row to look.
*(pointerArray[i] + j) basically means: "Find the beginning of the ith row of data in pointerArray, and then pick the jth element of that row, and give me that value.

Related

How to make a statement unnecessary with replace() in insertion-sort

I hope someone can help me out with this assignment. So we got this C++ algorithm by my professor:
template<class T> //Parameterized by the Type T
void insertion_sort(array<T>& A) //A is an array of Ts
//Permutes the elements of A into ascending sorted order
//The lower index bound of A is assumed to be 1
{ int n = A.size();
for(int k=2; k<=n; k++)
{ T x = A[k]; //x is a a variable of type T
//Insert x in the sorted sequence A[1], ..., A[k-1]
int i = k-1;
while (i>=1&&x<A[i]) //A[i] is evaluated only if i>=1
{ A[i+1]=A[i];
i--;
}
A[i+1]=x;
}
}
Ok. Now I have to use the function A.resize(0, n) between the lines 5 and 6 so that the statement "i>=1" in the while function becomes unnecessary. I understand that when this function is used the lower index bound of A becomes 0 instead of 1. But I do not see any use of that because I would still need that statement in the while. Does anyone have an idea?
I would be very grateful.
Thank you in advance!
To exclude i>=1 condition, you can move the smallest array element into the first position before the main loop.
Now this element becomes "sentinel" and it's presence excludes run out of array range.
If it is strictly needed to use your resize, then just set the smallest possible value (look at lowest) to new element with 0-th index.
We can not know about "magic" routines from some library

Replace entire row of a 2D array with another 1d array

I am trying to replace an entire row of a 2d array with another vector.
My code is currently as follow:
#include <stdio.h>
int main(){
int imax = 5;
int jmax = 5;
double x[imax][jmax] = {0.0};
double a[imax] = {1,2,3,4,5};
}
In other words, now my x is a matrix with 5x5. How do I add/append/rewrite the 1st row of X with my a vector?
Thanks
One way to copy the row "without a loop" is the std::copy standard library algorithm.
std::copy(a, a + imax, x[0]); // x[0] is the first row
The algorithm contains the loop. Depending on the implementation this might emit a single call to memcpy or memmove instead.
imax and jmax should be const to make that code legal. Anyways, one obvious possibility is to copy elements one by one like this:
for ( int j = 0; j < jmax; j++ ) {
x[row][j] = a[j];
}
Another way is to use memcpy. That should be faster in normal circumstances, however, you rely on the assumption that the square bracket [] operator was not overloaded. Also you only can overwrite one row this way, not a column, so be careful when and where you use that.
memcpy( x[row], a, sizeof(a) );
('row' is your variable where you put the index of the row you want to replace)

Use 2d Array with diffrent size of 2-nd row C++

Currently i'm tring to do 2d array in c++ that can have diffrent second column size. This is my code:
int **testZadanie;
testZadanie = new int*[testy];
...
for (int i = 0; i<testy; i++)
{
cin >> liczbaLakomczuchow >> liczbaCiastek;
testZadanie[i] = new int[liczbaLakomczuchow];
for (int j = 0; j<liczbaLakomczuchow; j++)
{
cin >> czasJedzenia;
//testZadanie[i, j] = czasJedzenia; this not works
*testZadanie[i, j] = czasJedzenia;
}
}
But when I want to attach values for each column i got exception. So i'm not sure if I can do this what i actually trying do ? ( declaring dynamic column element for each row and attach for each item in row ? )
Use x[y][z] instead of x[y, z].
When you write *x[y, z], the compiler interprets it as x[z][0] (which is not what you want) because:
a, b is a comma operator, which evaluates both operands and returns the value of the second one.
*a is equivalent to a[0].
This answer generally applies to builtin types only. You can overload ,, * and [] operators for a class, changing their behaviour completely.
If you don't know what operator overloading is, just ignore this remark.

c++ multidimensional array layout on stack and on heap

on stack:
string array3d1[x][y][z];
as far as I know, internally on the stack it's actually a one dimensional array.
on heap:
string * * * array3d2;
array3d2 = new string * * [x];
for (int i = 0; i < x; i++)
{
array3d2[i] = new string * [y];
for (int j = 0; j < y; j++)
{
array3d2[i][j] = new string [z];
}
}
on heap it's array of array of array.
Questions:
(1) what's the index of array3d1[a][b][c] ?
(2) when I use below syntax to access array3d1 and array3d2:
array3d1[a][b][c];
and
array3d2[a][b][c];
how does the compiler know the right element to access since they are in different layout?
what's the index of array3d1[a][b][c]?
If you mean what is the value of &array3d1[a][b][c] - (string*)array3d1, it's equal to a*y*z + b*z + c.
how does the compiler know the right element to access since they are in different layout?
The compiler knows, because array3d1 and array3d2 have different types.
array3d1 has type array of size x of arrays of size y of arrays of size z of string, so array3d1[a] has the type array of size y of arrays of size z of string and is located at ath index of original array, that is a*y*z string*s from its beginning. And so on other indices are applied.
array3d2 has type pointer to pointer to pointer to string, and indexing is done accordingly.

Treats for the cows - bottom up dynamic programming

The full problem statement is here. Suppose we have a double ended queue of known values. Each turn, we can take a value out of one or the other end and the values still in the queue increase as value*turns. The goal is to find maximum possible total value.
My first approach was to use straightforward top-down DP with memoization. Let i,j denote starting, ending indexes of "subarray" of array of values A[].
A[i]*age if i == j
f(i,j,age) =
max(f(i+1,j,age+1) + A[i]*age , f(i,j-1,age+1) + A[j]*age)
This works, however, proves to be too slow, as there are superfluous stack calls. Iterative bottom-up should be faster.
Let m[i][j] be the maximum reachable value of the "subarray" of A[] with begin/end indexes i,j. Because i <= j, we care only about the lower triangular part.
This matrix can be built iteratively using the fact that m[i][j] = max(m[i-1][j] + A[i]*age, m[i][j-1] + A[j]*age), where age is maximum on the diagonal (size of A[] and linearly decreases as A.size()-(i-j).
My attempt at implementation meets with bus error.
Is the described algorithm correct? What is the cause for the bus error?
Here is the only part of the code where the bus error might occur:
for(T j = 0; j < num_of_treats; j++) {
max_profit[j][j] = treats[j]*num_of_treats;
for(T i = j+1; i < num_of_treats; i++)
max_profit[i][j] = max( max_profit[i-1][j] + treats[i]*(num_of_treats-i+j),
max_profit[i][j-1] + treats[j]*(num_of_treats-i+j));
}
for(T j = 0; j < num_of_treats; j++) {
Inside this loop, j is clearly a valid index into the array max_profit. But you're not using just j.
The bus error is caused by trying to access array via negative index when j=0 and i=1 as I should have noticed during the debugging. The algorithm is wrong as well. First, the relationship used to construct the max_profit[][] array should is
max_profit[i][j] = max( max_profit[i+1][j] + treats[i]*(num_of_treats-i+j),
max_profit[i][j-1] + treats[j]*(num_of_treats-i+j));
Second, the array must by filled diagonally, so that max_profit[i+1][j] and max_profit[i][j-1] is already computed with exception of the main diagonal.
Third, the data structure chosen is extremely inefficient. I am using only half of the space allocated for max_profit[][]. Plus, at each iteration, I only need the last computed diagonal. An array of size num_of_treats should suffice.
Here is a working code using this improved algorithm. I really like it. I even used bit operators for the first time.