Sorry there are many similar questions but I just can't work out what I'm doing wrong (amateur alert!).
I'm trying to fill two arrays within a function then get the information back in main. I declare the arrays in main but need to assign them memory in the function (which works out how big they should be). Although the arrays seem to fill fine and I can print them from within the function, I get a segmentation fault when I try to print them from main.
I've tried to troubleshoot in this simplified program with a function that fills one array - it has the same problem. I assume I'm stuffing up my pointers - what am I doing wrong?? Here is the code and the output:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
void *make_v(double num, double *v)
{
int i;
v = (double *)calloc(5,sizeof(double));
for (i=0; i<5; i++) {
num += 5;
v[i] = num;
}
printf("IN: ");
for (i=0; i<5; i++)
printf("%lf ", v[i]);
printf("\n");
}
main(int argc,char **argv)
{
double *v=NULL;
double num=10.0;
int i;
make_v(num, v);
printf("OUT:\nv:[");
for (i=0; i<5; ++i) {
printf("%lf ", v[i]);
}
}
This outputs: IN: 15.000000 20.000000 25.000000 30.000000 35.000000 OUT: Segmentation fault
I'm coding in linux if that makes a difference...
Hope someone can help, thanks!
double *make_v(double num)
{
int i;
v = (double *)calloc(5,sizeof(double));
for (i=0; i<5; i++) {
num += 5;
v[i] = num;
}
printf("IN: ");
for (i=0; i<5; i++)
printf("%lf ", v[i]);
printf("\n");
retrun v;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.