Error in function and address pointer in string pointers

Viewed 22

I'm trying to create a program to find the length of string but the function name and char address seemed to always return an error

#ifndef LENGTH_STRING
#define LENGTH_STRING

#include<stdio.h>

int lengthString(char*){
    int i;
    i = 0;
    while ((*(char + i)) != '\0'){
        i += 1;
    }
} 

#endif

Error in function name: unnamed prototype parameters not allowed when body is present error in + sign: expected a ")" Error before ! sign: Expected an expression

1 Answers

char + i makes no sense. You meant to use the parameter, but you didn't give it a name!

You also forgot to return the size.

Fixed:

int lengthString( char *str ) {
    int i;
    i = 0;
    while ( (*(str + i) != '\0'){
        i += 1;
    }

    return i;
} 

There are many improvements we can make.

  • size_t is more appropriate for the size of memory blocks.
  • Accepting constant strings is more flexible.
  • my_strlen is more descriptive since you're recreating strlen.
  • No reason to have the initialization of i on a different line.
  • x[y] is so much clearer than 100% equivalent *(x+y).
  • ++i is shorter than i += 1.
size_t my_strlen( const char *str ) {
    size_t i = 0;
    while ( str[i] != '\0' ) {
        ++i;
    }

    return i;
} 

We can keep going by removing some useless bits.

size_t my_strlen( const char *str ) {
    size_t i = 0;
    while ( str[i] )
        ++i;

    return i;
} 

for is just a fancy while.

size_t my_strlen( const char *str ) {
    for ( size_t i=0; str[i]; ++i )
        /* nothing */;

    return i;
} 

We could even use

size_t my_strlen( const char *str ) {
    for ( size_t n=0; *(str++); ++n )
        /* nothing */;

    return n;
} 
Related