I have a task. I must create a function which has specific arguments (int readArray(FILE *wp, char *name, int n, double M[n][n]). I must read an array name from a file and put in an array of pointers, then I must read an array and put their value into an array. I try to run my program, but I get a segmentation fault.
Also in my file, I have the second array, so I must know, how to put them to another array(arr2), but I must read from the fifth line. How to do this? I think about using a scanf and in this scanf, I would ask the user from which line he wants to read, but I don't know how to do that. Or maybe I should try to detect string, and if I detect a second-string I would read from a second-string
This is my program
Code:
#include <stdio.h>
#include <stdlib.h>
int readArray(FILE *wp, char *name, int n, double M[n][n])
{
int i = 0, j;
fscanf(wp, "%s", &name[0]);
printf("Print name: %s", name);
return 0;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
fscanf(wp, "%lf", &M[i][j]);
printf("Print array: %s", name);
}
int main (int argc, char *argv[])
{
FILE *wz;
int n = 3;
char *name[1];
char *name2[1];
double arr[n][n];
double arr2[n][n];
if (argc != 2) {
printf("Wrong arguments number\n");
printf("I should run this way:\n");
printf("%s source\n",argv[0]);
exit(1);
}
if( (wz= fopen(argv[1],"r")) == NULL) {
printf("Open error %s\n", argv[1]);
exit(1);
}
readArray(wz, *name, n, arr);
readArray(wz, *name2, n, arr2);
int fclose(FILE *wz);
int fclose(FILE *wc);
return 0;
}
This is my text file, which I have:
Code:
arr1
9 8 7
6 5 4
3 2 1
arr2
1 2 3
4 5 6
7 8 9
When I read only name -everything is fine
Code:
#include <stdio.h>
#include <stdlib.h>
int readArray(FILE *wp, char *name)
{
int i = 0, j;
fscanf(wp, "%s", &name[0]);
printf("Print name: %s", name);
return 0;
}
int main (int argc, char *argv[])
{
FILE *wz;
int n = 3;
char *name[1];
if (argc != 2) {
printf("Wrong arguments number\n");
printf("I should run this way:\n");
printf("%s source\n",argv[0]);
exit(1);
}
if( (wz= fopen(argv[1],"r")) == NULL) {
printf("Open error %s\n", argv[1]);
exit(1);
}
readArray(wz, *name);
int fclose(FILE *wz);
int fclose(FILE *wc);
return 0;
}
When I read only array, when I use this txt file
and this program
Code:
#include <stdio.h>
#include <stdlib.h>
int readArray(FILE *wp, int n, double M[n][n])
{
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
fscanf(wp, "%lf", &M[i][j]);
printf("Two Dimensional array elements:\n");
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
printf("%f ", M[i][j]);
}
}
return 0;
}
int main (int argc, char *argv[])
{
FILE *wz;
int n = 3;
double arr[n][n];
if (argc != 2) {
printf("Wrong arguments number\n");
printf("I should run this way:\n");
printf("%s source\n",argv[0]);
exit(1);
}
if( (wz= fopen(argv[1],"r")) == NULL) {
printf("Open error %s\n", argv[1]);
exit(1);
}
readArray(wz, n, arr);
int fclose(FILE *wz);
int fclose(FILE *wc);
return 0;
}