K
K
Konstantin Malyarov2016-04-19 13:48:39
C++ / C#
Konstantin Malyarov, 2016-04-19 13:48:39

What did I not understand with the functions from the string.h library?

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

int main(){
  char string1[40];
  char string2[40];
  fgets(string1, 40, stdin);
  fgets(string2, 40, stdin);
  int i = strstr(string1, string2);
  printf("Hello World!");
  return 0;
}

All functions from the package return an int. 0 - if false, or cell number in the address. But when compiling, it says:
Invalid conversion from 'chars*' to 'int'.
What is the reason?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
abcd0x00, 2016-04-19
@abcd0x00

All functions from the package return an int.

Firstly, string.h is not a package, but a set of declarations for a group of functions from the standard library of C language functions. That is, the library includes all functions in general, and declaration files allow you to connect (declare) them only with the necessary groups.
Second, not all string manipulation functions return an int. It's you who came up with something mixed up somewhere. String functions are different - and returning int, and returning char *, and returning size_t. The strstr() function returns char * - a pointer to the beginning of the found substring, or NULL if the substring was not found.
If you need to determine the position of the found substring in a string, then you need to subtract the beginning of the entire string from the address of this substring.

N
Nikolai Romanovich, 2016-04-19
@MikalaiR

ptrdiff_t i = string1 - strstr(string1, string2);

K
Kirill Penzin, 2016-04-19
@kir_vesp

See documentation. Tyk
I will not say for everything, but usually functions from string.h return null, or a pointer to a cell. To get the cell number, you need to take their difference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question