Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Differences between strchr() and index()

I am doing something in C which requires use of the strings (as most programs do).

Looking in the manpages, I found, at string(3):

SYNOPSIS

#include <strings.h>

char * index(const char *s, int c)

(...)

#include <string.h>

char * strchr(const char *s, int c)

So I curiously looked at both strchr(3) and index(3)...

And I found that both do the following:

The strchr()/index() function locates the first occurrence of c in the string pointed to by s. The terminating null character is considered to be part of the string; therefore if c is '\0', the functions locate the terminating '\0'.

So, the manpage is basically a copy & paste.

Besides, I suppose that, because of some obfuscated necessity, the second parameter has type int, but is, in fact, a char. I think I am not wrong, but can anyone explain to me why is it an int, not a char?

If they are both the same, which one is more compatible across versions, and if not, which's the difference?

like image 880
ssice Avatar asked Nov 03 '10 21:11

ssice


People also ask

What is Strchr () in c programming?

Description. The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.

Is Index function in c?

The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.

How do I find the index of a character within a string in c?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string); Note that the result is zero based, so in above example it will be 2.

What does the Strchr STR c function return?

The strchr() function returns a pointer to the first occurrence of character c located within s. If character c does not occur in the string, strchr() returns a null pointer.


1 Answers

strchr() is part of the C standard library. index() is a now deprecated POSIX function. The POSIX specification recommends implementing index() as a macro that expands to a call to strchr().

Since index() is deprecated in POSIX and not part of the C standard library, you should use strchr().

The second parameter is of type int because these functions predate function prototypes. See also https://stackoverflow.com/a/5919802/ for more information on this.

like image 76
James McNellis Avatar answered Oct 02 '22 18:10

James McNellis