English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

eg:
/* function returning pointer to int */
int *func(int x, float y);

2006-06-14 18:46:58 · 4 answers · asked by QUEST-pRAC 1 in Computers & Internet Programming & Design

4 answers

Let me put together a quick function to show you where it might come in handy.

int * FindHighest(int * array, int size)
{
int * highest = array;
for (int * ptr = array; ptr - array < size; ptr++)
if (*ptr > *highest)
highest = ptr;

return highest;
}

// Now we have a function that returns a pointer to the highest item. Suppose we had some sort of levelling algorithm:

int MyFunction()
{
const int datasize = 200;
int data[datasize];

/* lots of code here that loads up the array */

// Subtract one from highest value
int * high = FindHighest(data, datasize);

// Now, since we have a pointer to the largest, we can update it and the update will update the array
(*high)--;
}

It's a simple example, but you'll notice that by returning a pointer we gave the calling function immediate control over the data. This can be a good thing or a very dangerous thing--but that's in essence what happens when you return a pointer.

Another thing to remember is that if you return a pointer to something you create with a new function, the calling function must know to delete it.

Hope this helps. Good luck.

2006-06-14 19:13:59 · answer #1 · answered by Mantis 6 · 0 0

It allows you to modify the memory pointed to by the pointer. Returning a pointer to an integer means that you expect the calling function to modify that integer at some point.

2006-06-16 03:24:47 · answer #2 · answered by waylandbill 3 · 0 0

Pointers have to be used while returning arrays (1D or multi dimensional). Returning pointer or array is same because internally arrays are pointers.

2006-06-14 19:35:04 · answer #3 · answered by Anonymous · 0 0

i think u r talkign about function pointer. They were used to make TSR (terminate and stay resident programs) like antiviruses.

2006-06-14 19:16:12 · answer #4 · answered by Shahzad Ahmed 2 · 0 0

fedest.com, questions and answers