[英]Segmentation Fault
i want to find the Length of a String without Using strlen() function.我想在不使用 strlen() 函数的情况下找到字符串的长度。 but it gives me segmentation fault error.
但它给了我分段错误。
#include <stdio.h>
#include <string.h>
unsigned string_length(char str[])
{
int i;
printf("Enter a string:");
scanf("%s",&str);
for (i = 0; str[i] != '\0';++i)
{
}
printf("Length of string: %d", i);
return i;
}
int main()
{
int ausgabe;
char str[100];
ausgabe = string_length(str[100]);
return 0;
}
This is what i did, i have tried with all possible variations (all i know (while, for, even with if)) but non of them seem to be the answer to my problem.这就是我所做的,我尝试了所有可能的变化(我所知道的(同时,为了,即使有如果))但它们似乎都不是我问题的答案。 I am new to programming and would welcome advice from professionals
我是编程新手,欢迎专业人士的建议
Don't need to pass &str to scanf("%s",&str);不需要将 &str 传递给 scanf("%s",&str); only pass str (without reference operator) to scanf.
只将 str(没有引用运算符)传递给 scanf。 Also, the better way to create a function is like following (see input parameters of string_length function):
此外,创建函数的更好方法如下(请参阅 string_length 函数的输入参数):
#include <stdio.h>
#include <string.h>
unsigned string_length(char str[])
{
int i;
//printf("Enter a string:");
//scanf("%s",&str);
for (i = 0; str[i] != '\0';++i)
;
//printf("Length of string: %d", i);
return i;
}
int main()
{
int ausgabe;
char str[100];
printf("%s", "Enter a string:");
scanf("%s",str);
ausgabe = string_length(str);
printf("Length of string: %d\n", ausgabe);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.