Pages

Saturday, March 19, 2011

Tricky, generic function pointer

#include
/* This is our generic function pointer */
typedef void (*fp)(void);
int func1(int a)
{
printf("Inside Func 1. Received %d\n", a);
return 2;
}

char func2(char b)
{
printf("Inside Func 2. Received %c\n", b);
return 'b';
}

int main()
{
fp ptr1;
int temp1;
char temp2;

ptr1 = (fp) func1;

temp1 = ((int (*)(int)) ptr1)(1);
ptr1 = (fp) func2;
// ptr1('g');
temp2 = ((char (*)(char))ptr1)('a');
printf("Inside Main. Received %d %c\n", temp1, temp2);
return 0;
}

Passing a function pointer to a function

#include

int any_function(int(*pfun)(int, int), int x, int y){
return pfun(x, y);
}

int sum(int x, int y){
return x + y;
}

int product(int x, int y){
return x * y;
}

int difference(int x, int y){
return x - y;
}

int main(void){
int a = 10;
int b = 5;
int result = 0;
int (*pf)(int, int) = sum; /* Pointer to sum function */

result = any_function(pf, a, b);
printf("\nresult = %d", result );

result = any_function(product,a, b);
printf("\nresult = %d", result );

printf("\nresult = %d\n", any_function(difference, a, b));
return 0;
}

Simple function pointer in C

#include

int sum(int x, int y){

return x + y;

}

int product(int x, int y){

return x * y;

}

int difference(int x, int y){

return x - y;

}

int main(void){

int a = 10;

int b = 5;

int result = 0;

int (*pfun[3])(int, int); /* Function pointer array declaration */


/* Initialize pointers */

pfun[0] = sum;

pfun[1] = product;

pfun[2] = difference;


/* Call all three functions through pointers in an expression */

result = pfun[1](pfun[0](a, b), pfun[2](a, b));

printf("\n\nThe product of the sum and the difference = %d\n", result);

return 0;

}


Some string manipulations is shell script

var="hai hello world tom"

pattern output
echo ${var%%hello*} //hai
echo ${var%%tom} //hai hello world
echo ${var##*hello} //world tom
echo ${var##hello*} //hai hello world tom
echo ${#var} // 19

Some shell script Experiments

1. Capture Ctrl+c Signal using Shell script

trap 'echo pressed c' 2

read f


2. Getting current PID using shell script

#!/bin/sh

echo $$

3. Use of arrays in shell script

newmap['name']="Abc"

newmap['designation']="SSE"

newmap['company']="xyz"


echo ${newmap['company']}

echo ${newmap['name']}

echo "after"

newmap=(Abd SSE HRD)

echo ${newmap[0]}

echo ${newmap[1]}

echo ${newmap[2]}

for i in newmap

do

echo $i

done