i am new in c programming and i just learn about pointer and string,i know when working with pointer and string we must allocate memory for string we want do declared using dynamic memory allocation.I want to calculate length of string without using c function library strlen().but why this below code doesn't give the real length of string,instead when i change *string to string[50] that means i am using array way to calculate,the code works fine and give me the real length of string.
this the code:
#include <stdio.h>
#include <stdlib.h>
int len(char *string);
int main(void){
char *string;
string=(char *)malloc(len(string+1));
puts("enter string:");
fgets(string,sizeof(string),stdin);
printf("length=%d\n",len(string));
return 0;
}
int len(char *string){
int len;
while(*string!='\0'){
string++;
len++;
}
return len-1;
}
this is when i run that code:
enter string:
programming
length=2
len. Compile with (mild) optimization and all reasonable warning flags (in GCC,-O -Wall, possibly a bit more). It should tell you about mistakes like the above.