Error in covering from int to int*

Asked

Viewed 173 times

1

I wanted to know why you are causing the error:

Error converting int to int*'

This program is only for training the use of pointers in parameters.

void teste(int *t){

*t = 50;
}   

int main(){

int x = 10;

cout << "Sem usar o metodo com ponteiro: " << x << endl;

teste(x);

cout << "Usando o metodo com ponteiro: " << x << endl;  

return 0;   
}
  • What you got from setting pointers?

  • Well the pointer is a variable that stores the address of another, I can manipulate whatever variable in which part of my code wants, this is the idea I learned about pointers

  • But you need to declare this pointer in your code and define which variable it will handle.

  • Ah then can only use a pointer parameter, being a pointer? I pass the address of the virile X to a pointer, and use the pointer in the function?

  • @Renanustolin The answer solved 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

2

I only had to say that you want to pass the address and not the value, after all the function is expecting an address of a value and not the value itself. We use the &.

void teste(int *t) {
    *t = 50;
}   

int main() {
    int x = 10;
    cout << "Sem usar o metodo com ponteiro: " << x << endl;
    teste(&x);
    cout << "Usando o metodo com ponteiro: " << x << endl;   
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Look if it’s not too much to ask, could you tell me some situation that is useful using pointers as parameters?

  • Pure C++ pointer if not required by the function you are using almost never, it is best to use reference or a smart pointer. But if you use it, it’s because you don’t want to transfer the value, it’s where the value is. When you need a change made to the called function to reflect on the calling function variable. You create an indirect. https://answall.com/q/181032/101

Browser other questions tagged

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