i want to find the Length of a String without Using strlen() function. 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); only pass str (without reference operator) to scanf. Also, the better way to create a function is like following (see input parameters of string_length function):
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.