1

Suppose I want to make a function like

int indexOf ( char * str, char c )
{
   // returns the index of the chracter c in the string str 
   // returns -1 if c is not a character of str
  int k = 0;  
  while (*str)
  { 
      if (*str == c) break;
      else ++str;
  }
  return *str ? k : -1;  
}

but I want to make it as reliable as possible. For instance, the above only works if the largest int is guaranteed to be greater than or equal to the maximum size of a character array. How can I cover all my bases in pure C?

3 Answers3

8

size_t

No, seriously. size_t is a standard C type. It's defined in <stddef.h>.

(that was the answer to "What is the equivalent of “size_t” in C?")

For the exact function like you wrote, strchr would be more suitable - the caller could use it like this:

const char* str = "Find me!find mE";
char* pos = strchr(str, '!');
if(pos) // found the char
{
    size_t index = (pos - str); // get the index
    // do the other things
}
else
{
    // char not found
}

So, in general, if you want to find something in the array provided by user, returning a pointer is most idiomatic in C.

You could return ssize_t (which includes all the possible values of size_t, and -1), but it's not standard C, so I don't recommend it. I only mention it for completeness.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • 1
    I think OP would be curious of how to deal with `return -1` part of his code. – Sergey Kalinichenko Apr 30 '15 at 14:57
  • 1
    OP is aware of size_t existing. However your answer doesn't show how to return a -1 or equivalent. – 2501 Apr 30 '15 at 15:02
  • @2501 I think that the question only need how to know if the char is in the string and the index. If the return is different to -1, while you know which is the return that confirm what you want is ok. (However, you are correct) – Shondeslitch Apr 30 '15 at 15:06
4

Use a pointer.

You will always be able to return a pointer to a valid element in an array. The not-found condition is signaled by returning a NULL.

2501
  • 25,460
  • 4
  • 47
  • 87
0

Interpreting your question as:

How to not rely in index size for pointer arithmetic?

The answer would be:

int indexOf ( char * str, char c )
{
    // returns the index of the chracter c in the string str 
    // returns -1 if c is not a character of str
    char *aux = str;  
    while (*aux != c )
    { 
        if (*aux == '\0')
            return -1;
        aux++;
    }
    return aux - str; 
}
Jonatan Goebel
  • 1,107
  • 9
  • 14