0
#include <stdio.h>
int length(char *point)
{
    int n=0;


    if (*point!='\0')
    {
        point++;
        n++;
    }
    return n;

}
void main()
{

    int m;
    char *point;
    char chars[80];
    printf ("please enter a chars\n");
    gets(chars);
    point=chars;
    m=length(chars);

    printf("The length of the chars is %d.\n",m);

}

I want to ask why the "n" can't be added? I think the problem is about the use of point,but i can't find it. Thanks.

2 Answers2

6
size_t length(const char *point)
{
    size_t n = 0;       
    while (*point != '\0') // Need to loop to iterate through point
    {
        point++;
        n++;
    }
    return n;
}

I would use it in the main like that :

int main(void)
{
    char chars[80];
    printf ("Please enter a chars\n");

    scanf("%79s", chars); 
    // The 79 is there to limit the input to the size you allocated in chars[80]
    // Thus avoiding buffer overflow

    size_t m = length(chars);
    printf("The length of the chars is %zu.\n",m);
    return 0;
}

You forget to iterate through the string. You incremented the pointer but that's all. Also, I recommend using strlen() which does exactly what you intend to do.

Using strlen():

int main(void)
{
    char chars[80];
    printf ("Please enter a chars\n");
    scanf("%79s", chars);
    size_t m = strlen(chars);
    printf("The length of the chars is %zu.\n", m);
    return 0;
}
Badda
  • 1,329
  • 2
  • 15
  • 40
0

You don't have a loop inside your function length(). The if is only evaluated once.

Add (or replace the if with) a loop statement

/* loop */ {
    if (*point!='\0') { /* ... */ }
}
pmg
  • 106,608
  • 13
  • 126
  • 198