You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单词搜索游戏代码崩溃问题及用户输入单词嵌入矩阵实现咨询

Hey there! Let's work through your Word Search Game problems step by step—first fixing that crash when inputting words, then figuring out how to embed those words into the matrix.


1. Fixing the Crash During Word Input

The crash happens for a few small but critical reasons in your newPuzzle function:

  • Wrong argument to scanf_s: When passing a char array to scanf_s, you don't need the & operator—word already acts as a pointer to the first element of the array. Using &word passes a pointer to the entire array, which is not what scanf_s expects.
  • Missing buffer size in scanf_s: Unlike regular scanf, scanf_s requires you to specify the maximum number of characters to read (to prevent buffer overflow). Since your word array is size 7, we need to pass 7 as the third argument.
  • Missing function prototypes: You call newPuzzle() and showPuzzle() in main before declaring them, which confuses the compiler. We'll add prototypes at the top of the file.
  • Missing header for getch(): The getch() function needs the <conio.h> header on Windows systems.

Here's the fixed newPuzzle function (we'll expand it later to handle word placement):

#include <conio.h> // Add this for getch()

// Add function prototypes before main
int newPuzzle(char Matrix[10][10]);
int showPuzzle(char m[10][10]);

// ... rest of main ...

int newPuzzle(char Matrix[10][10]) {
    char userWords[4][7]; // Store 4 words, each up to 6 chars + null terminator
    int i;
    
    system("cls");
    printf("Enter 4 words of your choice to be entered in the puzzle (max 6 characters each): \n");
    
    for (i = 0; i < 4; i++) {
        printf("Enter word %d: ", i + 1);
        // Fix scanf_s: pass word array directly and specify buffer size
        scanf_s("%s", userWords[i], 7);
        // Optional: Convert input to uppercase to match matrix characters
        for (int j = 0; userWords[i][j] != '\0'; j++) {
            userWords[i][j] = toupper(userWords[i][j]);
        }
    }
    
    // Next step: Place these words into the Matrix (we'll add this below)
    placeWordsInMatrix(Matrix, userWords);
    
    printf("Puzzle created successfully! Press any key to return to menu...");
    getch();
    return 0;
}

2. Embedding Words into the Matrix

To place words into the 10x10 matrix, we'll create a helper function placeWordsInMatrix that handles:

  • Randomly choosing a placement direction (horizontal left-to-right, vertical top-to-bottom, diagonal down-right)
  • Checking if the word fits in the chosen position (doesn't go out of matrix bounds)
  • Writing the word's characters into the matrix

Add this helper function to your code:

// Helper function to place words into the matrix
void placeWordsInMatrix(char Matrix[10][10], char userWords[4][7]) {
    // Directions: 0 = horizontal, 1 = vertical, 2 = diagonal
    int dir;
    int startRow, startCol;
    int wordLen;
    
    for (int w = 0; w < 4; w++) {
        wordLen = strlen(userWords[w]);
        // Skip empty words (just in case)
        if (wordLen == 0 || wordLen > 10) continue;
        
        // Keep trying until we find a valid position
        int valid = 0;
        while (!valid) {
            dir = rand() % 3;
            startRow = rand() % 10;
            startCol = rand() % 10;
            
            // Check if the word fits in the chosen direction
            if (dir == 0) { // Horizontal
                if (startCol + wordLen <= 10) valid = 1;
            } else if (dir == 1) { // Vertical
                if (startRow + wordLen <= 10) valid = 1;
            } else { // Diagonal
                if (startRow + wordLen <= 10 && startCol + wordLen <= 10) valid = 1;
            }
        }
        
        // Now place the word into the matrix
        for (int c = 0; c < wordLen; c++) {
            if (dir == 0) {
                Matrix[startRow][startCol + c] = userWords[w][c];
            } else if (dir == 1) {
                Matrix[startRow + c][startCol] = userWords[w][c];
            } else {
                Matrix[startRow + c][startCol + c] = userWords[w][c];
            }
        }
    }
}

Don't forget to add the prototype for this helper function too, near the top:

void placeWordsInMatrix(char Matrix[10][10], char userWords[4][7]);

Full Modified Code

Putting it all together, here's the complete working code:

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>

// Function prototypes
int newPuzzle(char Matrix[10][10]);
int showPuzzle(char m[10][10]);
void placeWordsInMatrix(char Matrix[10][10], char userWords[4][7]);

int main(void) {
    srand((unsigned)time(NULL));
    char Matrix[10][10];
    
    // Initialize matrix with random uppercase letters
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            Matrix[i][j] = (rand() % (91 - 65)) + 65;
        }
    }
    
    int menuChoice;
    do {
        system("cls");
        puts("WORD SEARCH GAME PUZZLE");
        puts("-----------------------");
        puts("1. New Puzzle");
        puts("2. Show Puzzle");
        puts("3. Exit");
        puts("-----------------------");
        printf("Select your choice: ");
        scanf_s("%d", &menuChoice);
        
        switch (menuChoice) {
            case 1: 
                newPuzzle(Matrix); 
                break;
            case 2: 
                showPuzzle(Matrix); 
                break;
            case 3:
                printf("Exiting game...");
                break;
            default:
                printf("Invalid choice! Press any key to try again...");
                getch();
        }
    } while (menuChoice != 3);
    
    return 0;
}

int newPuzzle(char Matrix[10][10]) {
    char userWords[4][7]; // Store 4 words (max 6 chars each)
    int i;
    
    system("cls");
    printf("Enter 4 words of your choice to be entered in the puzzle (max 6 characters each): \n");
    
    for (i = 0; i < 4; i++) {
        printf("Enter word %d: ", i + 1);
        scanf_s("%s", userWords[i], 7);
        
        // Convert input to uppercase to match matrix
        for (int j = 0; userWords[i][j] != '\0'; j++) {
            userWords[i][j] = toupper(userWords[i][j]);
        }
    }
    
    // Place the words into the matrix
    placeWordsInMatrix(Matrix, userWords);
    
    printf("\nPuzzle created successfully! Press any key to return to menu...");
    getch();
    return 0;
}

void placeWordsInMatrix(char Matrix[10][10], char userWords[4][7]) {
    int dir, startRow, startCol, wordLen;
    
    for (int w = 0; w < 4; w++) {
        wordLen = strlen(userWords[w]);
        if (wordLen == 0 || wordLen > 10) continue;
        
        int valid = 0;
        while (!valid) {
            dir = rand() % 3;
            startRow = rand() % 10;
            startCol = rand() % 10;
            
            // Check bounds for each direction
            if (dir == 0) { // Horizontal
                valid = (startCol + wordLen <= 10);
            } else if (dir == 1) { // Vertical
                valid = (startRow + wordLen <= 10);
            } else { // Diagonal (down-right)
                valid = (startRow + wordLen <= 10 && startCol + wordLen <= 10);
            }
        }
        
        // Write the word to the matrix
        for (int c = 0; c < wordLen; c++) {
            switch(dir) {
                case 0: Matrix[startRow][startCol + c] = userWords[w][c]; break;
                case 1: Matrix[startRow + c][startCol] = userWords[w][c]; break;
                case 2: Matrix[startRow + c][startCol + c] = userWords[w][c]; break;
            }
        }
    }
}

int showPuzzle(char m[10][10]) {
    system("cls");
    printf("  ");
    for (char c = 'A'; c <= 'J'; ++c) {
        printf("%c ", c);
    }
    printf("\n\n");
    
    for (int i = 0; i < 10; i++) {
        printf("%d ", i);
        for (int j = 0; j < 10; j++) {
            printf("%c ", m[i][j]);
        }
        printf("\n");
    }
    
    printf("\nPress any key to return to menu...");
    getch();
    return 0;
}

Key Notes:

  • The matrix is initialized with random uppercase letters first, then user words overwrite those positions.
  • We convert user input to uppercase so words match the matrix's character case.
  • The placement logic ensures words don't go out of the matrix bounds by checking valid positions before writing.
  • Added a default case in the menu to handle invalid inputs gracefully.

内容的提问来源于stack exchange,提问作者Bleach101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:46:23