統計字串中空格數量是經典指針練習,但原代碼使用 gets 並混用 C/C++ I/O,存在緩衝區溢出、未初始化指針、編譯器警告等多重問題。本文重構為現代、安全、標準的 C 寫法,並解析核心邏輯。
char *str; 未分配內存,gets(str) 寫入野指針 → **未定義行為,極易崩潰**。gets **C11 已移除**,無長度限制,必導致緩衝區溢出。printf/cout、iostream/stdio.h,風格混亂。system("PAUSE") 平台相關,非標準。#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1024
int main(void) {
char str[MAX_LEN] = {0};
int count = 0;
printf("Input a string: ");
fflush(stdout); // 確保提示先顯示
// fgets 讀整行,含換行符,安全限制長度
if (fgets(str, sizeof(str), stdin) == NULL) {
fprintf(stderr, "Read error\n");
return EXIT_FAILURE;
}
// 可選:移除尾部換行符
size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') str[len - 1] = '\0';
// 指針遍歷統計空格
for (const char *p = str; *p != '\0'; ++p) {
if (*p == ' ') ++count;
}
printf("Your input string is: %s\n", str);
printf("The Count of space = %d\n", count);
return EXIT_SUCCESS;
}
// 指針版(推薦,語義清晰、無索引變量、易優化)
for (const char *p = str; *p; ++p) if (*p == ' ') ++count;
// 下標版(等價)
for (size_t i = 0; str[i]; ++i) if (str[i] == ' ') ++count;
// 標準庫算法版(C++,C 需手寫)
// count = std::count(str, str + strlen(str), ' ');
若需統計空格、Tab、換行等所有 isspace 字符:
#include <ctype.h>
// ...
for (const char *p = str; *p; ++p) if (isspace((unsigned char)*p)) ++count;
注意:isspace 參數需轉 unsigned char 避免負值未定義行為。
gcc -std=c11 -Wall -Wextra -O2 space_count.c -o space_count
./space_count
fgets + 固定緩衝區或動態分配。for (const char *p = s; *p; ++p) 是 C 風格字串處理的標準慣用法,簡潔高效。