trilobite
December 7th, 2010, 08:36 PM
Hi all -
I've written a small program which does a "map" on an array, applying a function to each element and putting the result in a new array. Only problem is - the length of the array is not calculated correctly.
Here's the code -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
/* A function to apply to an integer. */
int func(int val)
{
return pow(val,2) + 5;
}
void map(int array[], int (*fn)(int) )
{
/* Length of the array */
int len = sizeof(array) / sizeof(int);
/* An array to store the results */
int resarray[len] ;
int i;
for(i=0; i<len; i++)
{
resarray[i] = fn(array[i]);
printf("Array[%d] is %d, Result[%d] is %d\n", i, array[i], i, resarray[i]);
}
}
int main(void)
{
/* A function pointer to use */
int (*ptr)(int) ;
/* Point the function pointer at our function */
ptr = func;
int myarray[] = {2, 3, 5, 7, 11, 13, 17};
map(myarray, *ptr);
return 0;
}
When this is run, it only gives one row, as follows -
Array[0] is 2, Result[0] is 9
Why is this, and what can I do to ensure the array size is calculated correctly?
Many thanks in advance -
- trilobite
I've written a small program which does a "map" on an array, applying a function to each element and putting the result in a new array. Only problem is - the length of the array is not calculated correctly.
Here's the code -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
/* A function to apply to an integer. */
int func(int val)
{
return pow(val,2) + 5;
}
void map(int array[], int (*fn)(int) )
{
/* Length of the array */
int len = sizeof(array) / sizeof(int);
/* An array to store the results */
int resarray[len] ;
int i;
for(i=0; i<len; i++)
{
resarray[i] = fn(array[i]);
printf("Array[%d] is %d, Result[%d] is %d\n", i, array[i], i, resarray[i]);
}
}
int main(void)
{
/* A function pointer to use */
int (*ptr)(int) ;
/* Point the function pointer at our function */
ptr = func;
int myarray[] = {2, 3, 5, 7, 11, 13, 17};
map(myarray, *ptr);
return 0;
}
When this is run, it only gives one row, as follows -
Array[0] is 2, Result[0] is 9
Why is this, and what can I do to ensure the array size is calculated correctly?
Many thanks in advance -
- trilobite