P
P
pshevnin2021-11-28 18:21:53
C++ / C#
pshevnin, 2021-11-28 18:21:53

What is the correct way to use a pointer?

Good afternoon. I have a function that takes a pointer. int next_edge(edge_t *out_edge)
Inside the function, I get another pointer that points to the value I need. How can I make it so that by returning return 0 or 1, I can get the value of a "useful" pointer in the program, through the pointer that I take into the function? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-11-28
@pshevnin

When you pass a pointer to an object (to anything) into a function, this means that you can change this object in the function and all changes will be visible to the calling code.
If you need the calling code to see the new pointer, then pass a pointer to a pointer to the function:

int next_edge(edge_t **out_edge)
{
  edge_t * tmp = malloc(sizeof(edge_t));
  if(tmp)
  {
     *out_edge = tmp;
     return 1;
  }
  return 0;
}

But it's usually easier in this case to return a pointer in the return value. The calling code can compare the returned value with NULL to determine if the function returned a normal pointer or if an error occurred. This is done, for example, by the malloc() function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question