C Pointer Vector Search

Asked

Viewed 103 times

0

Consider a type that represents an employee of a company, defined by the following structure:

typedef struct funcionario Funcionario;
struct funcionario {
  char nome[81];     // Nome do funcionário
  float valor_hora;  // Valor da hora de trabalho em Reais
  int horas_mes;     // Horas trabalhadas em um mês
};

Write a function that does a binary search on a pointer vector for the type Funcionario, the elements of which are in alphabetical order of the names of the officials. This function should receive as parameters the number of employees, the vector and the name of the employee you want to search for, and should have as return value a pointer to the registration of the searched employee. If there is no employee with the name sought, the function should return NULL. The function must conform to the following prototype:

Funcionario* busca (int n, Funcionario** v, char* nome);

Follow my code, I can’t find the error.

#include <stdio.h>
#include <stdlib.h>

typedef struct funcionario Funcionario;

struct funcionario {
  char nome[81];
  float valor_hora;
  int horas_mes;
};

static int comp(char* a, Funcionario* b) { return strcmp(a, b->nome); }

Funcionario* busca(int n, Funcionario** v, char* nome) {
  int i, ini, fim, meio, cmp;
  ini = 0;
  fim = n - 1;
  while (ini <= fim) {
    meio = (ini + fim) / 2;
    cmp = comp(nome, v[meio]);
    if (cmp < 0)
      fim = meio - 1;
    else if (cmp > 0)
      ini = meio + 1;
    else
      return v[meio];
  }
  return NULL;
}

int main() {
  int i, n;
  char name[85];
  scanf("%d", &n);
  Funcionario* a[n];
  for (i = 0; i < n; i++) {
    Funcionario* vet = malloc(sizeof(Funcionario));
    a[i] = vet;
    scanf("%s", vet->nome);
    scanf("%d", &vet->horas_mes);
    scanf("%f", &vet->valor_hora);
  }
  scanf("%s", name);
  Funcionario* resp = busca(n, a, name);
  printf("%s\n", resp->nome);
  printf("%d %.1f\n", resp->horas_mes, resp->valor_hora);
}
  • 3

    You are assuming that the data entry will be in alphabetical order but you are not doing any kind of validation of this obligation.

  • As long as the given values are sorted the code works correctly. Now I personally do not recommend reading lots of values without telling the user what to enter. Even for yourself the test level is easy to fail. Also missing the inclusion of <string.h> that may break in some cases.

No answers

Browser other questions tagged

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