|char * s| V |H|e|l|l|o|\0|So, unlike languages like Pascal or Java, nowhere in the string is stored its length. Instead, in order to find out a string's length, you call strlen(), from string.h. Here's an implementation of strlen():
[COLOR="Blue"]int[/COLOR] strlen([COLOR="Blue"]char[/COLOR] * s){
[COLOR="Blue"]int[/COLOR] i = [COLOR="Red"]0[/COLOR];
[COLOR="Magenta"]while[/COLOR](s[i] != [COLOR="Red"]'\0'[/COLOR])i++;
[COLOR="Magenta"]return[/COLOR] i;
}
strlen() returns the length of the string, not including the zero byte at the end. This is accomplished by going through it character by character until one reaches the zero byte, at which point the subscript is the length. So, how do you get a string from the user? Well, consider the following program:[COLOR="Green"]#include "stdio.h"
#include "stdlib.h"
#include "string.h"[/COLOR]
int main(){
[COLOR="Blue"]char[/COLOR] * str = malloc([COLOR="Red"]100[/COLOR]);
fgets(str, [COLOR="Red"]100[/COLOR], stdin);
fputs(str, stdout);
free(str);
}
Here we introduced several new functions: first, we used malloc(), from stdlib.h. malloc() is used to allocate memory, in other words get space for our string to be in. Here, we allocated 100 bytes of memory, lots of space for a line of input from the user.Next we call fgets(), which reads a line into a pre-allocated space of memory, from a stream given by the last argument. Because space is limited to what you allocate, fgets() takes a length as an argument, that prevents it from overfilling the array.
After that, we call fputs(), which prints the string to the supplied stream, ending at the zero byte, and free(), which automagically deallocates the right amount of memory.
Here is a piece of code which demonstrates some of the most common mistakes:
[COLOR="Blue"]int[/COLOR] main(){
[COLOR="Blue"]char[/COLOR] * str = malloc([COLOR="Red"]3000[/COLOR]); //don't allocate huge amounts of memory just for user input! at most, you need 200 bytes per line!
[COLOR="Magenta"]while[/COLOR](1){
gets(str); //don't use gets(): it can easily cause pointer errors!
[COLOR="Blue"]int[/COLOR] i = 0;
[COLOR="Magenta"]while[/COLOR](i < [COLOR="Red"]3000[/COLOR]){ // that's the end of the allocated region, not the string!
printf("at %d: \'%c\'",i,str[i]);
} // i must be incremented!
} // you didn't free the string! can cause errors later in development!
}


Sign In
Create Account


Back to top









