[英]What is causing this error in my C program (Segmentation fault (core dumped))?
I'm trying to create a little program (I'm still a beginner) which will create a histogram based on how frequent a letter of the alphabet (uppercase or lowercase) is found in a piece of text entered as an argument.我正在尝试创建一个小程序(我仍然是初学者),它将根据在作为参数输入的一段文本中找到字母(大写或小写)的频率来创建直方图。
Unfortunately, for some reason it keeps giving me a Segmentation fault (core dumped)
error when executing the a.out
file.不幸的是,由于某种原因,它在执行
a.out
文件时不断给我一个Segmentation fault (core dumped)
错误。
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void letter_count(char *str)
{
int i;
int count;
char letter;
i = 0;
count = 0;
letter = 'a';
while (str[i])
{
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] += 32;
i++;
}
i = 0;
while (letter <= 'z')
{
while (str[i])
if (str[i++] == letter)
count++;
ft_putchar(letter);
ft_putchar(' ');
while (count-- > 0)
ft_putchar('|');
ft_putchar('\n');
i = 0;
count = 0;
++letter;
}
}
int main(int argc, char **argv)
{
if (argc == 2)
letter_count(argv[2]);
else
write(1, "Error\n", 6);
return (0);
}
if (argc == 2)
letter_count(argv[2]);
is wrong.是错的。 If
argc
is 2, it means that there are two arguments, ie argv[0]
and argv[1]
如果
argc
为 2,则表示有两个参数,即argv[0]
和argv[1]
So try所以试试
letter_count(argv[1]);
BTW: When argc
is 2 then argv[2]
is NULL顺便说一句:当
argc
为 2 时, argv[2]
为 NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.