簡體   English   中英

strcmp for循環中的C分段錯誤

[英]C Segmentation Fault in strcmp for-loop

新手程序員學習C,在嘗試使用strcmp運行for循環時遇到了“分段錯誤(內核已轉儲)”錯誤。 我曾在strcmp上遇到過類似問題的問題,但似乎無法解決我的問題。 這是我編寫的程序。

#include<stdio.h>
#include<string.h>

int main() {
  char ftpstring[15];
  printf("\nEnter valid ftp command > ");
  fgets(ftpstring,15,stdin);

  const char* ftp[] = { "ascii", "recv", "send", "rmdir", "mkdir" , "pwd", "ls", "cd", "status", "quit" };

  for ( int i = 0; i <= 10; i++ ) {
    int comparison;
    comparison = strcmp(ftpstring, ftp[i]);
    if (comparison == 0 ) {
      printf("%s is a valid ftp command.", ftpstring);
      break;
    }
    if(i == 10) {
      printf("%s is NOT a valid ftp command.", ftpstring);
    }
  }
}

如您所見,該程序嘗試讀取用戶輸入以確定它是否與預定義的有效ftp命令之一匹配,然后返回是否匹配。

for ( int i = 0; i <= 10; i++ )應該是for ( int i = 0; i < 10; i++ )

ftp數組包含10個字符串,因此循環應從09包括)。

更一般的解決方案可能是

for ( int i = 0; i < sizeof(ftp)/sizeof(ftp[0]); i++ )

但是最好定義一個宏

#define FTP_NUM_OF_COMMANDS 10

並定義ftp數組,如下所示:

const char* ftp[FTP_NUM_OF_COMMANDS] = { "ascii", "recv", "send", "rmdir", "mkdir" , "pwd", "ls", "cd", "status", "quit" };

在這種情況下,編譯器還將驗證您沒有使用超過10個值來初始化它(錯誤)。 for循環將如下所示:

for ( int i = 0; i < FTP_NUM_OF_COMMANDS; i++ )

另請注意,以下代碼應移至for循環之外

if(i == FTP_NUM_OF_COMMANDS) {
  printf("%s is NOT a valid ftp command.", ftpstring);
}

i==FTP_NUM_OF_COMMANDS永遠不會在循環內部發生,如果該條件為true ,則for循環應該中斷。 確保在for循環范圍之外定義i for以便在for循環中斷后可用。

您正在對數組末尾進行比較: for循環應在9處停止,而您的循環將在數組末尾進行。

將10用作“魔術數”也不是一個好選擇:最好讓編譯器為您計算大小 最后,最好在循環使用index來確定是否已找到命令:

int index = -1;
for ( int i = 0 ; i != sizeof(ftp) / sizeof(*ftp) ; i++ ) {
    if (!strcmp(ftpstring, ftp[i])) {
        index = i;
        break;
    }
}
if (index == -1) {
    printf("%s is NOT a valid ftp command.", ftpstring);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM