The C language does not have a string type: it represents them via an array of
char
s, with a "special character" at the end which is a
null
value:
'\0'
This combines well with the lack of a boolean type, in that any non-zero value is
true
and a zero (or
null
) being false.
So it is pretty easy to identify the end of a "string" in a loop:
for (int i = 0; param_1[i]; i++) {}
You could use the pointer version instead of an array index, but that would require two increments instead of one.
You also need to fix the loop body, and return a value from the function if you want decent code.
I'd also recommend that the parameter should be a
const char*
instead of a
char *
:
#include <stdio.h>
int my_strlen(char* param_1)
{
int i;
for (i = 0; param_1[i]; i++)
{
}
return i;
}
int main()
{
const char* str = "hello world";
printf("%s:%u\n", str, my_strlen(str));
return 0;
}