struct myStruct {
int x;
float y;
char z;
};
struct myStruct StructVar; // myStructObj is a variable of type myStruct
// I want to store address of variable StructVar.
struct myStruct* p = & StructVar; // p is a pointer to a variable of type myStruct i.e StructVar here
int a=1, b=2, c=3, d=4, e=5;
int* p[5] = {&a, &b, &c, &d, &e}; // Here p is an array of 5 integer pointers.
// Print all the elements.
int i;
for( i = 0; i < 5; ++i) {
printf("%d ", *p[i]);
}
Requirement: I want to store address of function Fun in a variable.
void fun() {
printf("Void function\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
void (*p)(); // p is a pointer to a function which accepts nothing and returns nothing.
p = fun; // Name of function gives address of the function. It is same as &func
p(); // Calling function fun() using function pointer
return 0;
}
2. Function pointer with argument.
int add(int x, int y) {
return x+y;
}
int _tmain(int argc, _TCHAR* argv[])
{
int (*q)(int,int); // q is a pointer to function which receives first argument as int, 2nd arg as int and returns an integer.
q = &add; // only name of function add is also valid. Just for demonostation purpose I kept &add
printf("Sum = %d", q(10, 20));
return 0;
}
void Display(const char* p) {
while(*p != '\0') {
putchar(*p);
p = p + 1; // pointer + number = pointer
}
}
int _tmain(int argc, _TCHAR* argv[]) {
Display("Subrat");
Display("\tKumar");
Display("\tSwain\0DontPrint\n");
return 0;
}
void strrev(const char* p) {
int len = strlen(p);
p = p + len; // Here we are making the pointer to point to last charecter.
do {
putchar(*p);
p = p - 1;
} while(len--);
}
int _tmain(int argc, _TCHAR* argv[])
{
strrev("Subrat");
return 0;
}
int StrLen(const char* p) {
char* q = (char*)p;
while(*q != NULL) {
++q;
}
// Now q will point to last charecter
// p is pointng to first charecter
// We are interested in calcuating no of chars.
return (q - p); // POINTER - POINTER = NUMBER
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d", StrLen("Subrat"));
return 0;
}
int i = 10;
int* p = &i; // Let's say &i = 100
// p = 100 as &i = 100
p++; // Now p= p+1 = 100 + 1*sizeof(int) = 100 + 4 = 104;
p++; // Now p = 104 + 4 = 108
char c = 'a';
char* p = &c; // Let's say &c = 100
p++; // p = p +1 = 100 + 1*sizeof(char) = 100 + 1 = 101;
p++; // p = 101 + 1 = 102
double d = 10.5;
double* p = &d; // Lets say &d = 100
p++; // p = p + 1 = 100 + 1*sizeof(double) = 100 + 8 = 108
p++; // p = 108 + 8 = 116
struct Demo {
double a;
int b;
};
struct Demo* p;
p++; // it'll increment p by value(8+4 = 12)
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (1)
Author
Commented:Thanks.