Why doesn’t my Return return the i do for?

Asked

Viewed 66 times

4

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


int BuscaLinear(int *sequencia[], int tamanho, int valor)
{

    int i;
    for(i=0;i<tamanho;i++)
    {
        if(sequencia[i] == valor)
        {
            return i;
        }
    }
    return -1;
}

int main()
{
    int tamanho, valor, resultado, j;
    int sequencia[10] = {11,22,33,44,55,6,7,8,9,1};

    tamanho = 10;

    printf("Digite o valor a ser encontrado: \n");
        scanf("%d",&valor);

    resultado = BuscaLinear(sequencia, tamanho, valor);

    if(resultado != -1)
    {
        printf("O valor esta na posicao %d do vetor!",resultado);
    }
    else
    {
        printf("O valor não foi encontrado");
    }


    return 0;
}
  • The for loop does not count i++ and always returns -1 My IDE is code Blocks.

1 answer

5


Your way int BuscaLinear(int *sequencia[], int tamanho, int valor) is receiving a vector pointer. Declare so:

int BuscaLinear(int *sequencia, int tamanho, int valor)
//ou
int BuscaLinear(int sequencia[], int tamanho, int valor)

So when checking the value from within its vector, it will collect the integer value and not the vector position address.

  • Really you’re right. Thank you very much.

  • 1

    @Felipe if it worked, you can click on the green V side of the Brumazzi score, to accept the answer and mark as solved.

  • @Bacco I never used an online ide, I saw that it manages to find the value, thing that does not usually work on the pc, you would know the prq?

  • @Brumazzid.B. I tested it your way and it worked too, I think the compiler used in IDEONE must have some kind of optimization for these things. It shouldn’t work both ways, really, only yours. IDEONE is better for testing fast things anyway. Really, in these cases it is better to use a "real" compiler to test C

  • I believe that the explanation of this behavior that worked in IDEONE is due to the fact that, in their compiler, pointers and ints have the same size. In cases of divergence (as in code::Blocks), either the pointer had 64 bits or the int was 16 bits

Browser other questions tagged

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