What is the Definition of NULL in C?

Asked

Viewed 2,339 times

1

I was studying with my friend, and we are breaking our heads because we do not know what exactly the NULL function is! Because in every program that we see, NULL can serve in another way, I’m going to put a program here as an example:

#include <stdio.h>
#include <string.h>
int main() {
 char str1[21], str2[21];
 printf("Digite duas palavras: ");
 scanf(" %20[^\n] %20[^\n]", str1, str2);
 if (strstr(str1, str2) != NULL) {
 printf("%s ocorre em %s\n", str2, str1);
 }
 else {
 printf("%s NAO ocorre em %s\n", str2, str1);
 }
 return 0;
}

If (strstr(str1,str2)) != NULL? I didn’t understand that part, what do you mean?

  • 1

    The title of your question does not match your question in the last paragraph. The function strstr returns the pointer from where to find the substring in the larger string, and in the absence returns NULL

1 answer

3

Good afternoon, at the conference C the value NULL server to indicate that the pointer is not pointing to a value in memory.

Let’s say the first char array, str1, It’s like "cat dog food" and the second char array, str2, is "dog", what is the result of the function strstr ?

char str1[21] = "gato cachorro comida";
char str2[21] = "cachorro";

char[21] resultado = strstr(str1,str2);

The result will be the char array "food dog", the function strstr sought the first occurrence of str2, in str1 and found the occurrence resulting in the char array "dog food"".

So if the function did not find the occurrence it would return the value NULL

In your case you are testing if there is an occurrence str2 in str1 through the expression below:

if (strstr(str1,str2) != NULL) {
     //Executa este bloco de código se a ocorrência EXISTIR
}
else {
     //Executa este bloco de código se a ocorrência NÃO EXISTIR
}

I hope you understand!
If you want to master the subject more try to study Pointers in the C language

Browser other questions tagged

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