Basically, I'm saving some coordinates in 2 arrays, arrayX
and arrayY
. Then, I want to change the value of a "blank" matrix in the coordinates that are saved in the previously mentioned arrays.
Will post a simpler version of the code, just so you can understand:
float* arrayX = 0;
float* arrayY = 0;
int array_size = 0;
int width = 1440;
int height = 1080;
for (i=0;i<1234;i++){
if(flag==TRUE){
arrayX = realloc(arrayX, ++array_size * sizeof(*arrayX));
arrayY = realloc(arrayY, array_size * sizeof(*arrayY));
arrayX[array_size-1] = i
arrayY[array_size-1] = 100;
}
}
float *matrix1 = (float *)malloc(width * height * sizeof(float*));
for (i=0; i<width*height;i++){
*(matrix+i) = 0;
}
for (i=0; i<array_size; i++){
*(matrix1 + arrayY[i] * width + arrayX[i]) = 255; //ERROR HERE
}
This code gives me this error:
error: invalid operands to binary + (have 'float *' and 'float')
And I'm not understanding why:
arrayY[l]
is the float
pointed by arrayY + l
.
*(matrix1 + float * int + float)
should also be a float.
I'm clearly messing up something here, and I've scrolled to a fair share of other posts (on how to allocate the matrix, and with this error) and don't understand it/don't find exactly what I'm looking for.
I'm sure it's a pretty silly question, and with a very easy solution.
For starters the argument of the call of malloc in this declaration
float *matrix1 = (float *)malloc(width * height * sizeof(float*));
^^^^^^^^^^^^^^
is incorrect. It seems you mean
float *matrix1 = (float *)malloc(width * height * sizeof(float));
^^^^^^^^^^^^^
The pointer arithmetic is allowed between pointers and objects of integer types. However in this expression
*(matrix1 + arrayY[l] * width + arrayX[l])
you are using pointers and objects of the type float. So the compiler issues the error message.
From the C11 Standard (6.5.6 Additive operators)
2 For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)
So either use integer arrays or at least use casting as for example
*(matrix1 + ( int )( arrayY[l] * width + arrayX[l] ))