c - 在传递给 glutDisplayFunc() 的函数中打印全局指针值时程序退出

标签 c pointers glut

我想从用户那里获取一些顶点(x,y)的输入。为了存储输入,我使用了指向整数的双指针。接受输入后,我正在检查输入是否正确存储。

输入已正确存储,但是,传递给 glutDisplayFunc() 的函数中没有打印任何值,而是程序正在退出。

这是控制台输出:

Number of Vertices:3
Vertices (x, y):
100 0    // values entered by user
0 100
10 10
100 0    // values printed from takeInput()
0 100
10 10

Process finished with exit code -1073741819 (0xC0000005)    // maybe from myFunction()

这是我的代码:

#include <stdio.h>
#include <GL/glut.h>

GLint **points;
int n;

void takeInput(void) {
    printf("Number of Vertices:");
    scanf("%d", &n);

    GLint vertices[n][2], *ptrToVertices[n];
    printf("Vertices (x, y):\n");
    for (int i = 0; i < n; ++i) {
        scanf("%d%d", &vertices[i][0], &vertices[i][1]);
        ptrToVertices[i] = vertices[i];
    }
    points = ptrToVertices;

    /* check if input is stored correctly */
    for (int i = 0; i < n; ++i) {
        printf("%d %d\n", points[i][0], points[i][1]);
    }
}

void myFunction(void) {
    for (int i = 0; i < n; ++i) {
        printf("%d %d\n", points[i][0], points[i][1]);
    }
    // todo
}

void doGlutStuff(int argc, char **argv, char *title, void (*fun)(void)) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(1000, 1000);
    glutCreateWindow(title);
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(-500.0, +500.0, -500.0, +500.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0, 0.0, 0.0);
    glutDisplayFunc(fun);
    glutMainLoop();
}

int main(int argc, char **argv) {
    takeInput();
    doGlutStuff(argc, argv, "My Title", myFunction);
    return 0;
}

顺便说一下,这就是我编译代码的方式:

gcc myCode.c -lopengl32 -lfreeglut -lglu32

最佳答案

您正在将指向局部变量 (ptrToVertices) 的指针存储到全局变量 (points) 中。 takeInput 返回后,ptrToVertices 不再存在,您存储的指针将悬空。 (在这种情况下,它指向将被覆盖和重用的堆栈内存。当您取消引用 myFunction 中的 points 时,您会遇到导致崩溃的未定义行为。

一种解决方案是使用 malloc 为顶点分配空间,而不是使用局部变量。

关于c - 在传递给 glutDisplayFunc() 的函数中打印全局指针值时程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57701625/

相关文章:

c++ - glutGetWindow - 表达式必须有类类型

linux - 通过 ssh 在没有窗口的情况下在服务器上运行 OpenGL 程序

c - 努力弄清楚如何编写某个函数

python - 变量如何在 Python 中工作?

c++ - 如何在 OpenGL 中使用鼠标在相机周围移动?

带有对象指针的 C++ vector push_back

我可以使用 [][] 访问类型 int (*)[] 吗?

c - 使用 C 从数组中删除重复项

c++ - 从中序和先序遍历构造二叉树的时间复杂度

c - 如何只包含来自不同 C 文件的一个函数