notes 2

notes 2 - Pointer to functions: A generic array mapper that...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Pointer to functions: A generic array mapper that works for pointers of any type. //a generic function type typedef void (*Funcptr)(void*); //This function will call FuncPtr for every element in the array void genericArrayMapper(void *a, int n, int elemsize, FuncPtr *func){ for(int i=0;i<n;i++){ void *elemptr = (void*)((char*)a + i*elemsize); (*func)(elemptr); //call function for this element } } Example of using generic array mapper int accum; int sumInt(int *a){ //it accumulates the sum of all as in the accum accum+=*a; } void printInt(int *a){ //prints 1 int print(%d\n,*a); } int a={3.4.7.8}; main(){ int n=sizeof(a)/sizeof(int); int elemsize = sizeof(int); genericArrayMapper((void*)a,n,elemsize, printInt); //add entries accum = 0; genericArrayMapper((void*)a,n,elemsize,(FuncPtr*)sumInt); print(sum = %d\n,accum); } Lab1: Local vars-> stack Global vars( initialized) -> data Global vars( unitialized) -> bss Implementing multidimensional arrays using pointers 1) Simple 2D array...
View Full Document

Page1 / 4

notes 2 - Pointer to functions: A generic array mapper that...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online