sorry I've spent most of today trying to solve what is probably a simple pointer problem, was wondering if anyone could help.
I want a function that returns a number and an array to main(), therefore requiring the use of pointers for at least one of these. The array must be dynamically allocated inside the function.
I've tried to show my best attempt below in a simplified form. I just get "Segmentation Fault".
double my_func(double **ptr);
int main(int argc, char **argv){
double value;
double *a;
value = my_func(&a);
printf("Value is %f array[1] is %f \n", value, a[1]);
return 0;
}
double my_func(double **ptr){
int i;
/* generate an array */
void *memory = malloc(10*sizeof(double));
if (memory == NULL){
printf("ERROR: out of memory\n");
}
*ptr = (double *) memory;
/* Fill the array with some values */
for (i=0;i<10;i++)
{
**(ptr+i) = 42;
}
return 3.14;
}
[The reason for this is that I have a function that reads in a file, and I want to return the number of lines and an array containing the file contents to main(). I want it to dynamically allocate the array, such that the program will operate for any size file.]
Thanks for any help!