How to Returning Pointers in C and C++
Returning Pointers
Although functions that return pointers are handled just like any other type of function, a few important concepts need to be discussed.
Pointers to variables are neither integers nor unsigned integers. They are the memory addresses of a certain type of data. The reason for this distinction is because pointer arithmetic is relative to the base type. For example, if an integer pointer is incremented, it will contain a value that is 4 greater than its previous value (assuming 4-byte integers). In general, each time a pointer is incremented (or decremented), it points to the next (or previous) item of its type. Since the length of different data types may differ, the compiler must know what type of data the pointer is pointing to. For this reason, a function that returns a pointer must declare explicitly what type of pointer it is returning. For example, you should not use a return type of int * to return a char * pointer!
To return a pointer, a function must be declared as having a pointer return type. For example, this function returns a pointer to the first occurrence of the character c in string s:
/* Return pointer of first occurrence of c in s. */
char *match(char c, char *s)
{
while(c!=*s && *s) s++;
return(s);
}
If no match is found, a pointer to the null terminator is returned. Here is a short program that uses match():
#include
char *match(char c, char *s); /* prototype */
int main(void)
{
char s[80], *p, ch;
gets(s);
ch = getchar();
p = match(ch, s);
if(*p) /* there is a match */
printf(”%s “, p);
else
printf(”No match found.”);
return 0;
}
This program reads a string and then a character. If the character is in the string, the program prints the string from the point of match. Otherwise, it prints No match found.
Popularity: 1% [?]
Posted on December 13, 2009 at 8:01 am
i didn’t understand what you want to explain……..