c++ - 指针给出整个数组而不是C++ RayLib中的一个字符

标签 c++ arrays char raylib

我是C++的新手,因此决定首先使用RayLib作为图形引擎制作井字游戏。
下面的代码设置了一个屏幕,绘制了网格并检查了输入。
我正在处理的部分在单击的字段中显示X或O。
我终于有了绘制文本的程序,但是它似乎绘制了整个数组而不是一个字母。

#include "raylib.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
    //INITIALIZE//
    int screenWidth = 750;
    int screenHeight = 750;
    char matrix[9] = {'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'};
    char currentPlayer = 'X';
    InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
    SetTargetFPS(60);
    
    while (!WindowShouldClose())
    {   
        //INPUT//
        if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) {
            int mouseX = GetMouseX();
            int mouseY = GetMouseY();
            double x = floor(mouseX/250);
            double y = floor(mouseY/250);
            int index = x + 3*y;
            matrix[index] = currentPlayer;
            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        }
        //DRAWING//
        BeginDrawing();
        ClearBackground(WHITE);
        for (int i = 1; i < 3; i++) {
            int num = i*250;
            DrawLine(num, 0, num, screenWidth, LIGHTGRAY);
            DrawLine(0, num, screenHeight, num, LIGHTGRAY);
        }
        //Code I was working on
        for (int i = 0; i < 9; i++) {
            if (matrix[i] != 'E') {
                int textX = 115 + i*250 - (i%3)*750;
                int textY = 115 + (i%3)*250;
                char text = matrix[i];
                DrawText(&text, textX, textY, 20, LIGHTGRAY); //The problem is here
            }
        }
        EndDrawing();
    }
    CloseWindow();
    return 0;
}
当我单击左上角的单元格来绘制X时,它会绘制“XXEEEEEEEE0?D”。
有谁知道如何从数组中绘制一个字符?
提前致谢!

最佳答案

C风格的字符串以空字符(\0)终止,因此您必须添加该字符串,或者让它读取越界并调用未定义的行为。
因此,

char text = matrix[i];
应该
char text[] = {matrix[i], '\0'};
DrawText(&text, textX, textY, 20, LIGHTGRAY);
应该
DrawText(text, textX, textY, 20, LIGHTGRAY);
(先删除&,再删除text)

关于c++ - 指针给出整个数组而不是C++ RayLib中的一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63456410/

相关文章:

c++ - 二维索引异常

c++ - 如何编写通用函数来处理不同类型的流?

arrays - 如何在 Labview 中展平( reshape 为 1D)任意维度的数组

c++ - while 循环没有看到或找到终止空字符

c++ - 从字符串流复制到 char * 数组返回作为函数参数

c++ - SFML sprite 在制作多个纹理时是一个白色方 block

c++ - 查找表/数组索引的数据类型

JavaScript:在数组的 .length 上使用 defineProperty 访问器?

java - 每次从键盘(java)输入新数字时,如何将数字存储到数组中?

c - 从 C 中的非常量指针参数中释放字符串