Reputation: 136
I have a matrix of a layout
const int boatRect[MAX_BITMAP_SIZE][MAX_BITMAP_SIZE] = { // 5
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0}
};
and a struct with a pointer to it (matrix):
typedef struct bitmap {
Shape shape;
const int (*matrix)[MAX_BITMAP_SIZE];
int orientation;
int size;
} Bitmap;
I then want to transpose(part of the rotation process) the matrix in the struct:
void transpose(const int (*shape)[MAX_BITMAP_SIZE]) {
const int *temp;
for(int i = 0; i < MAX_BITMAP_SIZE; i++) {
for(int j = 0; j < i; j++) {
temp = (const int *) shape[i][j]; //Cast to 'const int *' from smaller integer type 'int'
shape[i][j] = shape[j][i]; //Read-only variable is not assignable
shape[j][i] = temp; //Read-only variable is not assignable
}
}
}
but I get those errors, I'm not sure of what I'm doing wrong!
I'm trying to do it this way to only have one matrix in the code and have pointers to it and rotate those pointers in a way that they convey the rotated matrix without creating another one.
So how do I in my Bitmap struct create a matrix of pointers that point to the const int matrix, and then rotate that matrix of pointers(not the one of int)?
Upvotes: 1
Views: 142
Reputation: 29126
Your matrix isn't a "matrix of pointers", which would be a matrix whose elements are pointers. It's a matrix of integers. You define it as an array of arrays of int
.
const int boatRect[MAX_BITMAP_SIZE][MAX_BITMAP_SIZE] = { ... };
Like other arrays, it can be represented as a pointer to its first element, which in your case is an array of MAX_BITMAP_SIZE
ints.
const int (*matrix)[MAX_BITMAP_SIZE];
Dereferencing it twice will give you an int
, namely the integer value at the given row and column. Therefore, your temp
variable for swapping should be an int
:
int temp = shape[i][j];
No casting necessary! (The warning means that int
s are "narrower" than a pointer on your system and that you will lose information in the assignment.)
With that change, the second error will still persist: You have made the matrix const
: The elements of a const T*
cannot be changed. If you want to modify the matrix in place, don't make it const
. (You can still make it locally const
in functions that access, but don't modify it.)
Upvotes: 2