[英]Read buffer as matrix using X and Y values in C
我有一個包含256個整數的緩沖區,因此創建了一個16x16的矩陣。 我要完成的工作是讀取存儲在緩沖區中的值,就像它是一個矩陣一樣。 因此,如果我給出5和3的坐標,則應該得到Y為5且Y為X的值。
例如,這是緩沖區的一小部分,但是在16x3的矩陣中以便於閱讀,請考慮將其作為起始索引0而不是1)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4
4 5 6 7 8 9 1 0 2 3 4 5 6 7 8 9
因此,如果我嘗試獲得Y = 2和X = 5的值,則應該返回值9。
這是我已經有的一些代碼,但是我的數學關閉了。
unsigned char getTablevalue(int tableIndex, unsigned char *buffer) {
return buffer[tableIndex];
}
void getInput(....) {
int yValue = 2;
int xValue = 5;
int returnValue = 0;
unsigned char *buffer = malloc(256 * sizeof (unsigned char));
memset(buffer, 0, 256);
... Some code to fill buffer...
returnValue = getTablevalue({what can I put here}, buffer);
}
任何幫助,將不勝感激! 先感謝您。
這演示了如何將緩沖區用作數組並將緩沖區“數組”復制到實際數組中。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
int x, y;
int arr[16][16];
int xtest =2, ytest =12; //'random values to test that it works
/* allocate space for a buffer of 256 values in the range 0 to 255) */
unsigned char *buffer = malloc(256 * sizeof (unsigned char));
/* fill the buffer with sequential values from 0 to 255 */
for (n = 0; n < 256; n++) {
buffer[n] = n;
}
/* just to check the fill was OK - print out the buffer contents */
for (n = 0; n < 256; n++) {
printf("%d .. ", buffer[n]);
}
printf("\n\n");
/* fill a 16 * 16 array with values from the buffer
that the buffer data is arranged in 16 groups of 16 values in a
single sequential buffer */
for (x = 0; x < 16; x++) {
for (y = 0; y < 16; y++) {
arr[x][y] = buffer[(x * 16) + y];
}
}
/* print out the array */
for (x = 0; x < 16; x++) {
for (y = 0; y < 16; y++) {
printf("%d\t", arr[x][y]);
}
printf("\n");
}
printf("\n\n");
/* just print a 'random' xy value from the matrix and from the buffer
they will be the same (we hope) */
printf("X=%d,Y=%d, Matrix[%d][%d] is: %d ... and Buffer %d,%d is %d\n",
xtest, ytest, xtest, ytest, arr[xtest][ytest],
xtest, ytest, buffer[(xtest * 16) + ytest]);
if (arr[xtest][ytest] == buffer[(xtest * 16) + ytest]) {
printf("Wow - they ARE the same\n");
} else {
printf("Oh No - they are different\n");
}
}
樣品輸出
X=2,Y=12, Matrix[2][12] is: 44 ... and Buffer 2,12 is 44 Wow - they ARE the same
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.