0

I'm trying to implement the following function but my code is not functional. Any ideas why?

int *colecao_pesquisa_nome(colecao *c, const char *nomep, int *tam);

Return an indices array referring to the position of all plants that present the full scientific name or any of the local names equal to nomep. Returns by reference the array’s size (tam). If it’s unsuccessful, the function should return NULL.

int *colecao_pesquisa_nome(colecao *c, const char *nomep, int *tam)
{   if(c==NULL || nomep==NULL)return NULL;
    long i=0,a,z=0,y=0;
    int *indice=NULL;
    
    for (i = 0; i < c->tamanho; i++)
    {
        if (strstr(c->plantas[i]->nome_cientifico, nomep)!= NULL)
        {
            indice=(int*)realloc(indice,sizeof(int)*(z+1));
            indice[z]=i;
             z=z+1;
        }
    
        if(strstr(c->plantas[i]->nome_cientifico, nomep) == NULL){
            for(a=0;a<c->plantas[i]->n_alcunhas;a++){;
               if (strstr(c->plantas[i]->alcunhas[a], nomep) != NULL){
                   indice=(int*)realloc(indice,sizeof(int)*(z+1));
                   indice[z]=i;
                   z=z+1;
                   break;
                }
            }  
        }
    }
    *tam=z;
    return indice;
}
Jens
  • 69,818
  • 15
  • 125
  • 179
House
  • 1
  • 1
  • You `break;` after the second `if (...)`, but not after the first -- is that indented? – David C. Rankin Mar 28 '21 at 10:16
  • `*tam=sizeof(*indice);` -->> `*tam=z;` – wildplasser Mar 28 '21 at 10:54
  • tam should be equal do z but my program is finding the word where she is not so z is getting higher and higher so i cant use it but tam = sizeof(indice) is not right too , i only do the break in the second because i only need to find the word once – House Mar 28 '21 at 14:10
  • Need structure definitions. – Joshua Mar 28 '21 at 18:36
  • In `if (strstr(c->plantas[i]->nome_cientifico, nomep)!= NULL) ... if(strstr(c->plantas[i]->nome_cientifico, nomep) == NULL)` that second if could just be the word `else`, couldn't it? – Jerry Jeremiah Mar 28 '21 at 20:44
  • I am not sure but https://en.cppreference.com/w/c/memory/realloc says `reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc()...` And your first `realloc` call reallocates a pointer pointing to void. I don't think that's allowed. Maybe when you call realloc you should test for NULL and malloc instead? – Jerry Jeremiah Mar 28 '21 at 20:48

0 Answers0