为什么这段C语言程序中第一个gets()的输入会丢失?
Hey there, let's break down why your program's anystr is ending up empty and fix it step by step.
The Root Causes of the Problem
Your code has two critical issues that lead to the unexpected behavior:
1. Array Overwriting Due to Insufficient Size
- You declared
char srchstr[1];— but when you usegets()to read input into it, even a single character plus the required null terminator ('\0') needs at least 2 bytes of space. When you input a character,gets()writes past the bounds ofsrchstr, corrupting adjacent memory (which happens to be whereanystris stored in your program's memory layout). - The unused
char tmp[1];also contributes to this memory layout mess, making the overwriting affectanystrdirectly.
2. Unsafe Use of gets()
The gets() function is extremely dangerous because it doesn't check the length of input against your array size. Even if you fix the array sizes, using gets() can still lead to buffer overflows. Modern compilers actually deprecate or outright ban gets() for this reason.
Fixed Code
Here's a corrected version of your program with explanations of the changes:
#include <stdio.h> #include <string.h> // For strcspn() to handle newlines int main() { char anystr[10], srchstr[2]; // srchstr now has space for char + null terminator // Removed unused tmp array to clean up memory layout printf("Enter a string : "); fgets(anystr, sizeof(anystr), stdin); // Replace gets() with safe fgets() // Remove the newline character that fgets() includes anystr[strcspn(anystr, "\n")] = '\0'; printf("Enter any character you want to search in input string: "); fgets(srchstr, sizeof(srchstr), stdin); srchstr[strcspn(srchstr, "\n")] = '\0'; // Trim newline here too printf("anystr : %s\n", anystr); printf("anystr first character : %c\n", anystr[0]); printf("srchstr : %c\n", srchstr[0]); return 0; }
Key Changes Explained
- Increased array sizes:
srchstr[2]gives enough space for one character plus the mandatory null terminator. - Replaced
gets()withfgets():fgets()takes the array size as an argument, preventing buffer overflows. It reads until a newline or the array is full. - Trimmed newline characters:
fgets()includes the newline character (\n) in the input, so we usestrcspn()to find the newline and replace it with a null terminator to clean up the string. - Removed unused variables: The
tmparray was unnecessary and could interfere with memory layout, so we got rid of it.
Alternative Simplification for Single Character Input
If you only need a single search character, you can skip using an array entirely and use a char variable with getchar() instead:
// Replace the srchstr array with this: char srchchar; printf("Enter any character you want to search in input string: "); srchchar = getchar(); // If there's a leftover newline in the buffer, consume it while (getchar() != '\n');
This avoids array size issues entirely for the single character input.
内容的提问来源于stack exchange,提问作者MRZ

