First of all, let's rewrite your code a little bit, for the sake of removing some confusion (because to the uninitiated there are few things going on here, that might seem similar, but are not).
#include <string.h>
void print_as_according_to_strlen(char *n) {
for (int i=0; i < strlen(newstring); i++) {
printf("a");
}
}
There, this is the relevant part. If you look at the definition of strlen
you'll see, that it returns a value of type size_t
size_t strlen(const char *s);
Return the length of the string s.
size_t
is an unsigned type. C and C++ have certain rules by which integer values are implicited converted to a "common" type when used together in an operation. These are the so called "integer promotion rules" – those are important to know, and you absolutely must learn them.
One of those rules is, that if you make a signed integer "interact" with an unsigned integer, the promoted type will be unsigned as well. And of course if you attempt to promote a negative value to an unsigned type, the result will be something different.
Now with C things become tricky here, because there are some (actually the majority of cases) where attempting to do that invokes undefined behavior, i.e. anything may happen. There are however a few exceptions, where it's actually well behaved (for example if you have two unsigned variables unsigned a = 3
and unsigned b = 5
the result of the operation a-b
is actually a well defined value, because unsigned overflow is well defined, and the result is UINT_MAX - (b-a)
).
The bottom line for you is: You must rewrite your code so that the comparison promotes to either a signed comparison, or instead of starting from -1
, go to strlen(…)+1
. Instead of using an int
I suggest you use a ptrdiff_t
instead, because the size of an int may, or may not, be sufficient to hold the result of strlen
. And by happenstance (not of C, but how modern OSs manage memory) strlen
will never return a value that could overflow ptrdiff_t
ptrdiff_t len = strlen(newstring);
for(ptrdiff_t i=-1; i < len ; i++){