Pass vector as argument to a function

Asked

Viewed 164 times

-1

I’m trying to pass a vector to a C function, but I don’t know what I’m doing wrong.

Since the code is small, I’ll post in full:

#include <stdio.h>

int calcula(double A){
    if(A<=10.0){
        resposta = A;
    }

    return resposta;
}

int main(){     
    double A[100];
    int i;

    for(i=0; i<=99; i++){
        scanf("%lf", &A[i]);
    }      

    for(i=0; i<=99; i++){
        calcula(A[i]);
        printf("A[%d] = %.1lf\n",i, A[i]);
    }

    return 0;
}
  • 3

    Do you want to pass an array to which function? The function calcula? And what does this function have to do? Tell if the received element is less than or equal to 10? Find the first element with value less than or equal to 10? What are the elements with a value less than or equal to 10? Your code is easy and your problem is simple, but first we need to know exactly what you are trying to do so we can help.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

This code doesn’t make much sense, the question makes even less.

It’s not passing a vector, it’s passing a unique value. If you want to pass an array do this and treat it, but everything indicates that only pass the same value, and this is correct.

What is wrong is the internal code of the function. First we make relational comparison with a number double does not always work, it has no accuracy. Second is putting a value on resposta and that variable doesn’t even exist. so the compiler must be reporting this. If so, the variable isn’t even required.

Even if you declare a variable you need to initialize with an invalid value. What would it be? 0? A negative? A Nan? Something else? Then I’d have to change the kind of return.

To tell you the truth maybe you should just return true or false, or even that since the code is too simple. No matter what comes back if I have to filter something on main() must have a if there also, otherwise it even works, as long as you choose a value that will be invalid, but it will be printed normally if you don’t have a filter.

We can’t know exactly what the code should do, so it’s not possible to help any more than that, but the mistake is this that I demonstrated.

Browser other questions tagged

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