venkatesh said:
hai,
any can tell what is the advantge of using pointers?any increase in
speed or execution time?
if you know please tell what are the real time applications of data
structure?
thanks in advance
Pointers are necessary for a number of operations:
1. If you want to write to a function parameter and have that change
reflected in the caller, you must use pointers:
void swap_wrong(int a, int b)
{
int tmp = b;
b = a;
a = tmp;
}
void swap_right(int *a, int *b)
{
int tmp = *b;
*b = *a;
*a = tmp;
}
int main(void)
{
int x = 1, y = 2;
printf("before swap_wrong: x = %d, y = %d\n", x, y);
swap_wrong(x, y);
printf("after swap_wrong: x = %d, y = %d\n", x, y);
swap_right(&x, &y);
printf("after swap_right: x = %d, y = %d\n", x, y);
return 0;
}
2. The only way to track dynamically allocated memory is through a
pointer:
char *newString = malloc(newStringSize);
3. The only way to create struct types that refer to instances of
themselves is to use a pointer:
struct tree {
int value;
struct tree *left;
struct tree *right;
};
4. If you want to associate specific behaviors with specific data, you
can use pointers to functions:
/**
* Routines to parse data and calibration files for various
* scientific instruments
*/
int parseGraDat(char *fileName) {...}
int parseGraCal(char *fileName) {...}
int parseMstDat(char *fileName) {...}
int parseMstCal(char *fileName) {...}
int parsePwvDat(char *fileName) {...}
int parsePwvCal(char *fileName) {...}
/**
* Lookup table type to associate parse functions
* with file types and extensions
*/
struct parserLookup {
char *instrumentType;
char *extension;
int (*parser)(char *fileName);
};
/**
* Lookup table instance
*/
struct parseLookup lookupTable[] = {
{"GRA", "dat", parseGraDat},
{"GRA", "cal", parseGraCal},
{"MST", "dat", parseMstDat},
...
};
...
for (file = getFirstFileName(); file != NULL; file =
getNextFileName())
{
int i = getLookupIndex(lookupTable, file);
if (i >= 0)
{
if ((*lookupTable
.parser)(file) != 1)
{
printf("Error parsing %s\n", file);
}
}
}
5. All array types are converted to pointer types if the array appears
as a function parameter:
int foo(int *arr) {...}
int main(void)
{
int bar[10];
...
if (foo(bar)) {...}
...
return 0;
}
Technically, all array types are converted to pointer types if the
array appears in any context other than an array definition or as a
sizeof operand (I think there's one more that I'm forgetting).
Pointers *can* offer some optimization; instead of passing large
structs as function parameters, you can pass a pointer to the struct,
saving some overhead.