为int指针赋值时,为什么我的C程序崩溃了?

cve*_*omz 0 c pointers pass-by-reference

我试图让一个函数从我的main()函数传递一些整数指针并为它们赋值.但是,我的程序在分配值时崩溃.这是我的代码:

int computeMoveLocation(int* r, int* c, char* board)
{
    //some code up here
    *r = 0;    //This breaks the program
    *c = 0;
}
Run Code Online (Sandbox Code Playgroud)

我不是想改变指针的地址 - 我试图改变指向的整数的.但是,我显然做错了什么.

任何帮助将不胜感激.

编辑: 这是main()的相关代码.如果我还要包含其他任何内容,请告诉我.

int main()
{
    //initialization code
    //...

    while (1)
    {

        switch (MACHINE_STATE)
        {
            case COMPUTER_MOVE :
            {
               //check rows for three Xs
               //check columns for three Xs
               //check diagonals for three Xs
               //otherwise, move anywhere else
               int *r, *c;
               computeMoveLocation(r, c, board);
               computerMove(*r,*c, board);
               PREVIOUS_STATE = COMPUTER_MOVE;
               MACHINE_STATE = HUMAN_MOVE;
               break;
            }

            //Other cases
        }//end switch
    }//end while
}//end main
Run Code Online (Sandbox Code Playgroud)

Bar*_*klı 9

你正在传递指针,但你没有分配内存.所以他们指向内存中的随机位置.

int computeMoveLocation(int* r, int* c, char* board)
{
    //some code up here
    *r = 0;    //This breaks the program
    *c = 0;
}
Run Code Online (Sandbox Code Playgroud)

坏主要:

int main()
{
    int *r;
    int *c;
    char *board;
    // bad, passing in pointers but didn't allocate memory
    computeMoveLocation(r, c, board); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

好主要#1:

int main()
{
    int r = 5;
    int c = 5;
    char board = 'a';
    // fine, passing address of variables on stack
    computeMoveLocation(&r, &c, &board); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

好主要#2:

int main()
{
    int *r = malloc(sizeof(int));
    *r = 5;
    int *c = malloc(sizeof(int));
    *c = 5;
    char *board = malloc(sizeof(char));
    *board = 'a';
    // fine, passing pointers that point to heap
    computeMoveLocation(r, c, board); 

    free(r);
    free(c)
    free(board);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)