[英]Segmentation fault (core dumped) error for C program
I am trying to run below program in an online C compiler. 我正在尝试在在线C编译器中的程序下面运行。 But I get segmentation error.
但是我得到细分错误。 Can you help me fix this
你能帮我解决这个问题吗
#include <stdio.h>
#include <string.h>
int main()
{
char string[15] = "Strlwr in C";
printf("%s",tolower(string));
return 0;
}
Following is the prototype of tolower
以下是
tolower
的原型
int tolower(int c);
You should pass an int
or something like char
which can safely convert to int
. 您应该传递一个
int
或可以安全地转换为int
类似char
东西。 Passing char *
(Type of string
) like you do leads to UB. 像您一样传递
char *
( string
类型)会导致UB。
To convert a string to lowercase, you need to convert each character separately. 要将字符串转换为小写,需要分别转换每个字符。 One way to do this is:
一种方法是:
char string[15] = "Strlwr in C";
char lstr[15];
int i = 0;
do {
lstr[i] = tolower(string[i]);
} while(lstr[i] != '\0');
printf("%s", lstr);
You are using tolower
incorrectly. 您使用的
tolower
错误。 This function returns int
and gets int
as a parameter (here is it's declaration: int tolower(int c);
). 该函数返回
int
并获取int
作为参数(这是声明: int tolower(int c);
)。 What you want to do is call it on each char
of your char array
, and print each one: 您要做的是在
char array
每个char
上调用它,并打印每个:
char string[15] = "Strlwr in C";
for(int i = 0; i < strlen(string); i++)
printf("%c",tolower(string[i]));
Read cplusplus.com/reference/cctype/tolower It takes a single int as parameter, not char and not array. 阅读cplusplus.com/reference/cctype/tolower它使用单个int作为参数,而不是char和array。
You probably want to use a loop on "string", which processes each in turn. 您可能想在“字符串”上使用一个循环,该循环依次处理每个循环。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
int i;
char string[15] = "Strlwr in C";
for (i=0; i< sizeof(string)/sizeof(char); i++)
{
string[i]=(char)(tolower((int)string[i]));
}
printf("%s\n",string);
return 0;
}
Output: 输出:
strlwr in c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.