- Feb 3, 2005
- 7,326
- 2
- 76
I'm trying to create the following function (text from the homework):
2. In another program, write a function, int mystrlen (char * str), which takes a string argument (in C this is a char *) and finds the length of that string. To test your function, you can take your programs from homework 1 that use strlen, and replace it with your new function, mystrlen. You should see the same results.
Now, I've just recently started out with C. I've programmed in Java before, but there are some differences that make things "hard" for me (strings, pointers, etc). Now, I thought my code would work. Turns out it spits out some giant, horribly wrong number for "hello" (definitely doesn't say 5). If someone could help point me in the right direction, or tell me what I'm doing wrong, that'd be great. Here's my code:
#include <stdio.h>
int mystrlen(char *str){
int length;
int i = 0;
for(i; str[ i ] != '\0'; i++){
length++;
}
return length;
}
int main(int argc, char * argv[]){
printf("%d\n", mystrlen("Hello"));
return 0;
}
2. In another program, write a function, int mystrlen (char * str), which takes a string argument (in C this is a char *) and finds the length of that string. To test your function, you can take your programs from homework 1 that use strlen, and replace it with your new function, mystrlen. You should see the same results.
Now, I've just recently started out with C. I've programmed in Java before, but there are some differences that make things "hard" for me (strings, pointers, etc). Now, I thought my code would work. Turns out it spits out some giant, horribly wrong number for "hello" (definitely doesn't say 5). If someone could help point me in the right direction, or tell me what I'm doing wrong, that'd be great. Here's my code:
#include <stdio.h>
int mystrlen(char *str){
int length;
int i = 0;
for(i; str[ i ] != '\0'; i++){
length++;
}
return length;
}
int main(int argc, char * argv[]){
printf("%d\n", mystrlen("Hello"));
return 0;
}