gpt4 book ai didi

c - 使用 C 中的 X 和 Y 值将缓冲区读取为矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:26 25 4
gpt4 key购买 nike

我有一个包含 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] 是:44 ... 缓冲区 2,12 是 44
哇——它们是一样的

关于c - 使用 C 中的 X 和 Y 值将缓冲区读取为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com