Mail Archives: djgpp/2000/05/18/19:49:04
Alexei A. Frounze <alex DOT fru AT mtu-net DOT ru> wrote:
> Do I need to declare a variable of "size_t" type, if I want to know length
> of the string using strlen()???
If you want to store the value of the strlen() call: Yes, most
certainly you have to. If you don't, you risk breaking your program on
some platform, where it could usually have worked nicely. A simple
example: if the char* variable 'mystring' happens to point to string
of 40000 characters, and you do this:
int i;
int length = strlen(mystring)
/* set all of 'mystring' to the letter '-':
for (i=0; i< length; i++)
mystring[i] = '-';
you'll be quite confused by the result on a 16bit platform. Even worse would
have been
/* set the 10th-last letter to '+': */
mystring[length-10] = '+';
This one will usually crash the program, or overwrite content of other
variables totally unrelated to 'mystring'. Changing the types of 'i'
and 'length' to size_t gives working code.
> If so, how do I mix int and size_t then? Or I need to use size_t only, if I
> have problems with type casting???
You shouldn't generally need any type casting between int and
size_t. If at all, it'll usually be from int to size_t, not the other
way round. If you think you have to do that, chances are high that
you're just writing broken code.
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -