So I'm trying to create a simple array 2D inside a struct, and to read the values of some coordinates that are in a file.
At this moment I've got all inside functions and i get a segmentation fault when i try to get the coordinates on the 'get_coords' function. If I write all the exactly same code on a 'int main' instead of using functions it works.
code:
#include <stdio.h>
#include <stdlib.h>
// structure
typedef struct coordinates{
double **a;
} coord;
// counts the nmbr of points
int count(){
int i;
int a1, a2, a3;
FILE *fp;
fp = fopen("abc.txt", "r+");
while (fscanf(fp, "%d %d %d", &a1, &a2, &a3) != EOF){
i++;
if (feof(fp)){
break;
}
}
fclose(fp);
return(i);
}
// creates new structure with the right size of memory allocated
coord *newVector(size_t s){
coord *v;
int j;
v = malloc(sizeof(coord));
v->a = malloc(sizeof(double*)*3);
for (j=0; j<3; j++){
v->a[j] = malloc(sizeof(double)*s);
}
}
void get_coords(coord *points){
int i=0;
FILE *fp;
fp = fopen("abc.txt", "r+");
while (fscanf(fp, "%le %le %le", &points->a[i][0], &points->a[i][1], &points->a[i][2]) != EOF){
i++;
}
fclose(fp);
}
int main(){
int i = 0, j=0;
coord *points;
i = count();
points = newVector(i);
get_coords(points);
for (i=0; i<3; i++){
printf("%lf %lf %lf\n", points->a[i][0], points->a[i][1], points->a[i][2]);
}
}
abc.txt:
1 2 3
4 5 6
7 8 9
Thanks all for your help.
Cumps, Dylan.
PS: This is just a prototype for what i want.