String check inside a C function

Asked

Viewed 297 times

0

Greetings! I’m creating a C program where the user can change the state of some sensor by typing the sensor name and 1 or 0 to change the state of the sensor, being 1 for on and 0 for off. However, when I try to make this condition of checking out of main, in a function, it is not working, I believe it is some error in passing parameters, if you can help me, I will put the code below.

#include<stdio.h>
#include<string.h>
char y[2];
int sensor;
int s1;
char s[2];

void verificar(char y[2], int sensor);

void main ()
{
printf("Digite o sensor que deseja alterar o estado\n");
gets(s);
printf("Ligar ou desligar? (1 ou 0)\n");
scanf("%d", &s1);
void verificar(s, s1);
}

 void verificar(char y[2], int sensor)
{
if(strcmp(y,"s1")==0 && (s1 == 1))
{
    printf("S1 ligado");
}
}

When I try to run the program, the check does not occur.

  • 1

    calling the function is only with the name: verificar(s, s1); without the void

1 answer

1

Dude, your problem is you’re going over the vector by parameter. The correct way to receive an array per parameter is to receive its address, i.e., you need a pointer.

The second point is that to call a function you do not put the void.

With these changes your code worked:

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

char y[2];
int sensor;
int s1;
char s[2];

void verificar(char *y, int status){
    if(strcmp(y,"s1") == 0 && (status == 1)) {
        printf("S1 ligado");
    }
}

void main () {
    printf("Digite o sensor que deseja alterar o estado\n");
    gets(s);
    printf("Ligar ou desligar? (1 ou 0)\n");
    scanf("%d", &s1);
    verificar(s, s1);
}
  • There may be inconsistent behavior when the function return is not specified main, see more. The correct thing is to implement it this way int main(void) { /* ... */ } and you can return a value other than 0 in case the program fails.

Browser other questions tagged

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