Array Partition with pointer - c++

I have a 20 x 20 array and need to iterate over it by reading a 4 x 4 array. I thought I could do this with pointed assignment, but it does not do much except force close
const char SOURCE[20][20];
const char **pointer;
for(int x = 0; x < 20; x+=4)
{
for(int y = 0; y < 20; y+=4)
{
pointer = (const char **)&SOURCE[x][y];
printGrid(pointer);
}
}
void printGrid(const char **grid)
{
// do something usefull
}

Just casting a pointer to a different type doesn't change the
type of what it points to (and will usually lead to undefined
behavior, unless you really know what you're doing). If you
cannot change printGrid, you'll have to create an array of
pointers on the fly:
for ( int x = 0; x < 20; x += 4 ) {
for ( int y = 0; y < 20; y += 4 ) {
char const* p4[4] =
{
source[x] + y,
source[x + 1] + y,
source[x + 2] + y,
source[x + 3] + y
};
printGrid( p4 );
}
}

A pointer to a pointer is not the same as an array of arrays.
You can however use a pointer to an array instead:
const char (*pointer)[20];
You of course need to update the printGrid function to match the type.
As for the reason why a pointer-to-pointer and an array-of-array (also often called a matrix) see e.g. this old answer of mine that shows the memory layout of the two.

Your 2D-array is of type char:
const char SOURCE[20][20];
When you are iterating through it, you can either look at the char or reference the address with a char*:
for(int x = 0; x < 20; x+=4)
{
for(int y = 0; y < 20; y+=4)
{
printGrid(SOURCE[x][y]); // do this unless you need to do something with pointer
}
}
Then you can make printGrid with either of the following signatures:
void printGrid(const char& grid)
{
// do something usefull
}
or
void printGrid(const char* grid)
{
// do something usefull
}

Extending James's Answer, you may change your code as below as it sees that the it passes pointer to an array of 4 char rather than just array of char.
for(int x = 0; x < 20; x+=4)
{
for(int y = 0; y < 20; y+=4)
{
char const (*p4[4])[4] =
{
(const char(*)[4])(SOURCE[x] + y),
(const char(*)[4])(SOURCE[x + 1] + y),
(const char(*)[4])(SOURCE[x + 2] + y),
(const char(*)[4])(SOURCE[x + 3] + y)
};
}
}

Related

C++ get parameters before a for loop or not

What is the best practice in this case:
Should I get variables before running a for loop like this:
void Map::render(int layer, Camera* pCam)
{
int texture_index(m_tilesets[layer]->getTextureIndex());
int tile_width(m_size_of_a_tile.getX());
int tile_height(m_size_of_a_tile.getY());
int camera_x(pCam->getPosition().getX());
int camera_y(pCam->getPosition().getY());
int first_tile_x(pCam->getDrawableArea().getX());
int first_tile_y(pCam->getDrawableArea().getY());
int map_max_x( (640 / 16) + first_tile_x );
int map_max_y( (360 / 16) + first_tile_y );
if (map_max_x > 48) { map_max_x = 48; }
if (map_max_y > 28) { map_max_x = 28; }
Tile* t(nullptr);
for (int y(first_tile_y); y < map_max_y; ++y) {
for (int x(first_tile_x); x < map_max_x; ++x) {
// move map relative to camera
m_dst_rect.x = (x * tile_width) + camera_x;
m_dst_rect.y = (y * tile_height) + camera_y;
t = getTile(layer, x, y);
if (t) {
pTextureManager->draw(texture_index, getTile(layer, x, y)->src, m_dst_rect);
}
}
}
}
or is it better to get it directly in the loop like this (in this case the code is shorter but less readable):
void Map::render(int layer, Camera* pCam)
{
int first_tile_x(pCam->getDrawableArea().getX());
int first_tile_y(pCam->getDrawableArea().getY());
for (int y(first_tile_y); y < (640 / 16) + first_tile_x; ++y) {
for (int x(first_tile_x); x < (360 / 16) + first_tile_y; ++x) {
// move map relative to camera
m_dst_rect.x = (x * m_size_of_a_tile.getX()) + pCam->getPosition().getX();
m_dst_rect.y = (y * m_size_of_a_tile.getY()) + pCam->getPosition().getY();
Tile* t(getTile(layer, x, y));
if (t) {
pTextureManager->draw(m_tilesets[layer]->getTextureIndex(), getTile(layer, x, y)->src, m_dst_rect);
}
}
}
}
Is there an impact on performance using one method over another?
Syntactically the second version is to be preferred as it does contain the object in the scope where it is being used, not leaking it to different contexts. Performance wise you will need to profile but I'd be surprised if there was any difference at all because a compiler will often notice that the results don't change, at least for simple functions, and do this optimization for you.
For functions that are more complex or potentially dynamic, but you know they will not change their result during the for loop it makes sense to define them before the loop.

Cast from int to char

I'd like to know how this cast works :
int value = 100;
auto f = [&value] (int x, int y) -> char { return x + y + value; };
printf("%d\n", f(10, 20));
value = 200;
printf("%d\n", f(10, 20));
return 0;
It prints -126 and -30 but i don't understand how is it possible to print a negative integer.
The numerical range for char is -128..127. 10 + 20 + 100 is 130 and outside of that range, so it wraps around when expressed as char.
To fix you need to use a data type that can contain values large enough:
auto f = [&value] (int x, int y) -> int { return x + y + value; };
Or use values < 127.

Stack around the variable 'Yarray' was corrupted

When I declare an array to store the Y values of each coordinate, define its values then use each of the element values to send into a rounding function, i obtain the error 'Run-Time Check Failure #2 - Stack around the variable 'Yarray; was corrupted. The output is mostly what is expected although i'm wondering why this is happening and if i can mitigate it, cheers.
void EquationElement::getPolynomial(int * values)
{
//Takes in coefficients to calculate Y values for a polynomial//
double size = 40;
double step = 1;
int Yarray[40];
int third = *values;
int second = *(values + 1);
int first = *(values + 2);
int constant = *(values + 3);
double x, Yvalue;
for (int i = 0; i < size + size + 1; ++i) {
x = (i - (size));
x = x * step;
double Y = (third *(x*x*x)) + (second *(x*x)) + (first * (x))
Yvalue = Y / step;
Yarray[i] = int(round(Yvalue)); //<-MAIN ISSUE HERE?//
cout << Yarray[i] << endl;
}
}
double EquationElement::round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
// if n<0 then ceil(n-0.5) else if >0 floor(n+0.5) ceil to round up floor to round down
}
// values could be null, you should check that
// if instead of int* values, you took std::vector<int>& values
// You know besides the values, the quantity of them
void EquationElement::getPolynomial(const int* values)
{
//Takes in coefficients to calculate Y values for a polynomial//
static const int size = 40; // No reason for size to be double
static const int step = 1; // No reason for step to be double
int Yarray[2*size+1]{}; // 40 will not do {} makes them initialized to zero with C++11 onwards
int third = values[0];
int second = values[1]; // avoid pointer arithmetic
int first = values[2]; // [] will work with std::vector and is clearer
int constant = values[3]; // Values should point at least to 4 numbers; responsability goes to caller
for (int i = 0; i < 2*size + 1; ++i) {
double x = (i - (size)) * step; // x goes from -40 to 40
double Y = (third *(x*x*x)) + (second *(x*x)) + (first * (x)) + constant;
// Seems unnatural that x^1 is values and x^3 is values+2, being constant at values+3
double Yvalue= Y / step; // as x and Yvalue will not be used outside the loop, no need to declare them there
Yarray[i] = int(round(Yvalue)); //<-MAIN ISSUE HERE?//
// Yep, big issue, i goes from 0 to size*2; you need size+size+1 elements
cout << Yarray[i] << endl;
}
}
Instead of
void EquationElement::getPolynomial(const int* values)
You could also declare
void EquationElement::getPolynomial(const int (&values)[4])
Which means that now you need to call it with a pointer to 4 elements; no more and no less.
Also, with std::vector:
void EquationElement::getPolynomial(const std::vector<int>& values)
{
//Takes in coefficients to calculate Y values for a polynomial//
static const int size = 40; // No reason for size to be double
static const int step = 1; // No reason for step to be double
std::vector<int> Yarray;
Yarray.reserve(2*size+1); // This is just optimization. Yarran *Can* grow above this limit.
int third = values[0];
int second = values[1]; // avoid pointer arithmetic
int first = values[2]; // [] will work with std::vector and is clearer
int constant = values[3]; // Values should point at least to 4 numbers; responsability goes to caller
for (int i = 0; i < 2*size + 1; ++i) {
double x = (i - (size)) * step; // x goes from -40 to 40
double Y = (third *(x*x*x)) + (second *(x*x)) + (first * (x)) + constant;
// Seems unnatural that x^1 is values and x^3 is values+2, being constant at values+3
double Yvalue= Y / step; // as x and Yvalue will not be used outside the loop, no need to declare them there
Yarray.push_back(int(round(Yvalue)));
cout << Yarray.back() << endl;
}
}

C++: is this a correct way to use integer variables as pointers to a function call?

I am a C++ newbie.
Context: I found this third-party snippet of code that seems to work, but based on my (very limited) knowledge of C++ I suspect it will cause problems. The snippet is as follows:
int aVariable;
int anInt = 1;
int anotherInt = 2;
int lastInt = 3;
aVariable = CHAIN(anInt, anotherInt, lastInt);
Where CHAIN is defined as follows (this is part of a library):
int CHAIN(){ Map(&CHAIN, MakeProcInstance(&_CHAIN), MAP_IPTR_VPN); }
int _CHAIN(int i, int np, int p){ return ASMAlloc(np, p, &chainproc); }
int keyalloc[16384], kpos, alloc_locked, tmp[4];
int ASMAlloc(int np, int p, alias proc)
{
int v, x;
// if(alloc_locked) return 0 & printf("WARNING: you can declare compound key statements (SEQ, CHAIN, EXEC, TEMPO, AXIS) only inside main() call, and not during an event.\xa");
v = elements(&keyalloc) - kpos - 4;
if(v < np | !np) return 0; // not enough allocation space or no parameters
Map(&v, p); Dim(&v, np); // v = params array
keyalloc[kpos] = np + 4; // size
keyalloc[kpos+1] = &proc; // function
keyalloc[kpos+2] = kpos + 2 + np; // parameters index
while(x < np)
{
keyalloc[kpos+3+x] = v[x];
x = x+1;
}
keyalloc[kpos+3+np] = kpos + 3 | JUMP;
x = ASMFind(kpos);
if(x == kpos) kpos = kpos + np + 4;
return x + 1 | PROC; // skip block size
}
int ASMFind(int x)
{
int i, j, k; while(i < x)
{
k = i + keyalloc[i]; // next
if(keyalloc[i] == keyalloc[x]) // size
if(keyalloc[i+1] == keyalloc[x+1]) // proc
{
j = x-i;
i = i+3;
while(keyalloc[i] == keyalloc[j+i]) i = i+1; // param
if((keyalloc[i] & 0xffff0000) == JUMP) return x-j;
}
i = k;
}
return x;
}
EDIT:
The weird thing is that running
CHAIN(aVariable);
effectively executes
CHAIN(anInt, anotherInt, lastInt);
Somehow. This is what led me to believe that aVariable is, in fact, a pointer.
QUESTION:
Is it correct to store a parametrized function call into an integer variable like so? Does "aVariable" work just as a pointer, or is this likely to corrupt random memory areas?
You're calling a function (through an obfuscated interface), and storing the result in an integer. It might or might not cause problems, depending on how you use the value / what you expect it to mean.
Your example contains too many undefined symbols for the reader to provide any better answer.
Also, I think this is C, not C++ code.

C++ error: Double and 3d Vector

I got an error when compile the below code saying that "called object type 'double' is not a function or function pointer". Because 'position' is a 3d vector, so I was trying to access each element of the vector.
int k=1;
int m=1;
double x, y, z;
x=position.x;
y=position.y;
z=position.z;
for (int j = 3; j < 1000 ; j++)
{
x(j) = 2 * x(j-1) - x(j-2) + (delta_t * delta_t * (-1.0*k/m) * x(j-1));
}
You'll actually have to keep track of x(j), x(j-1), and x(j-2) all as separate variables (using the syntax x(j) is akin to calling a function x() with argument j, which is not what you want).
Try:
double xj, xj_m1, xj_m2;
xj_m1 = position.x;
xj_m2 = position.x;
for (int j = 3; j < 1000 ; j++) {
xj = 2 * xj_m1 - xj_m2 + (delta_t * delta_t * (-1.0*k/m) * xj_m1);
//Update xj_m2 and xj_m1 for the next iteration
xj_m2 = xj_m1;
xj_m1 = xj;
}
When you do it:
x=position.x;
You expect that position.x is an array?
To access to an element in a vector, you can use the [] operator:
std::vector<int> myIntVector = { 1, 2, 3 };
int i = myIntVector[0]; // i = 1 because myIntVector[0] is the first element of myIntVector
The variable position looks like a coordinate vector, so it's not an array, it's just a class / struct like this:
struct Vector3
{
double x, y, z;
};
In other words, position.x is just a number.