Total count of characters without strlen

Asked

Viewed 142 times

0

I need to count the total number of characters present in any word without the function strlen().

First I performed the word reading, after using a for to go through the word, within the for I used the while to add my counter while palavra in position [i] is different from null \0, however an error is happening, the program even opens, but does not execute anything. On the console it is reported that I am trying to compare a pointer to an integer, how could I solve this?

#include <stdio.h>
#include <string.h>

main()
{
char palavra[20];
int tam=0 ,i;

printf("\n Digite uma palavra: ");
gets (palavra);

for (i=0; i < palavra ;i++)
{
    while(palavra[i] != '\0')
    {
        tam ++;
    }
}   
printf("\n %d", tam);
}
  • 2

    i < palavra, i is a whole and palavra is a pointer, but even tidying up this will have problems with the while that will be infinite. Considering the word "abacate", i would start at zero and the while will perform while palavra[0] is different from '\0', which is always.

1 answer

1


The comparison performed in the i < palavra makes no sense and will generate a loop and yet in your code you wouldn’t leave the while never because the variable i is not being added in the while, one way to do it is to add up the values in the i in the while without using the for:

#include <stdio.h>
#include <string.h>

int main() {
    char palavra[20];
    int tam=0 ,i;

    printf("\n Digite uma palavra: ");
    gets (palavra);

    i = 0;
    while(palavra[i] != '\0')
    {
        i++;
        tam ++;
    }
    printf("\n %d", tam);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.