Pointer and pointer function in C

Pointer is pointing to a memory address that contains some value. To demonstrate:

Code:

#include <stdio.h>

int main(void) {
int *k;
int n=8;

k=&n;
printf(“the address of n is: %x\n”, k);
printf(“the value of n is: %d\n”, n);
printf(“the value of n pointing to address of n is: %d\n\n”, *k);

return 0;
}

pointer

Result:

the address of n is: 28fee8
the value of n is: 8
the value of n pointing to address of n is: 8

 

Now after introducing another variable m=17, we can see that the variable is contained right next to the address where k’s address value is contained. to clarify:

Code:

#include <stdio.h>

int main(void) {
int *k;
int n=8;
int m=17;

k=&n;
printf(“the address of n is: %x\n”, k);
printf(“the value of n is: %d\n”, n);
printf(“the value of n pointing to address of n is: %d\n\n”, *k);

printf(“now the address of k (k contains the address of n): %x\n”, &k);
printf(“the address next to k’s address: %x\n”, k+1);
printf(“the address 2nd next to k’s address: %x\n”, k+2);
printf(“the value contained in the address 2nd next address to k’s address: %d\n”, *(k+2));
return 0;
}

pointer1

Result:

the address of n is: 28fee4
the value of n is: 8
the value of n pointing to address of n is: 8

now the address of k (k contains the address of n): 28fee8
the address next to k’s address: 28fee8
the address 2nd next to k’s address: 28feec
the value contained in the address 2nd next address to k’s address: 17

 

Functional Pointer:

To demonstrate functional pointer we can see the following recursive function to find factorial. Here pointer is defined by:

long (*func_pointer)(int);
func_pointer=&factorial;

Code:

#include<stdio.h>

long factorial(int);

int main()
{
int n;
long f;

setbuf(stdout, NULL);
printf(“Enter an integer to find factorial\n”);
scanf(“%d”, &n);

long (*func_pointer)(int);
func_pointer=&factorial;

if (n < 0)
printf(“Negative integers are not allowed.\n”);
else
{
f = func_pointer(n);
printf(“%d! = %ld\n”, n, f);
}

return 0;
}

long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

Result:

Enter an integer to find factorial

4

4! = 24

 

 

LinkedInFacebookGoogle+Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>