[英]Segmentation Fault in C command line arguments while trying to add to array
我是 C 的新手,這個程序應該是 output usage: ./substitution key
當用戶輸入非字母鍵時。 在密鑰長度小於 27 個字母的情況下,應 output 一條消息,密鑰長度必須為 26 個字母。 如果用戶沒有輸入,則生成第一條錯誤消息。 不提供任何輸入正在工作,並打印有效的錯誤消息。 但是,如果我嘗試提供其他輸入,即向數組添加字符,則會顯示分段錯誤。 你能幫幫我嗎?
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
int main(int argc, char*argv[argc])
{
int counter = 0;
if (argc==1)
{
printf("Usage: ./substitution key\n");
}
for (int i = 1;i <= argc; i++)
{
if (isalpha(argv[i]) != 0)
continue;
else
counter++;
}
if (counter>1)
printf("Usage: ./substitution key\n");
else if (argc!=27 && argc!=1)
printf("key must contain 26 characters.\n");
}
您將超出數組邊界。 改變這個:
for (int i = 1 ;i <= argc; i++)
對此
for (int i = 1 ;i < argc; i++)
而且您濫用了 argv - 它是一個以空字符結尾的字符串數組。 數組的大小為argc,每個字符串的長度可以用strlen function得到。 例如,檢查以下代碼。
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc == 1) {
printf("Usage: ./substitution key\n");
}
const char *key = argv[1]; // for convenience
int counter = 0;
// count alphas
while (isalpha(key[counter])) { ++counter; }
// count length
int len = strlen(key);
// check if key consists of alphas
if (counter != len) {
printf("Usage: ./substitution key\n");
}
// check length
if (counter != 26) {
printf("key must contain 26 characters.\n");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.