#include <stdio.h>
#include <string.h>
int numExperiment=1;
int main(int argc, const char * argv[])
{
char* experiments[20];
int data[10][20];
char* input;
char* endof = "***END***";
do {
input=fgets(input, 20, stdin);
if (numExperiment%2 != 0) {
experiments[numExperiment-1]=strdup(input);
}
else {
int k=0;
while ((data[k][numExperiment-1]=strsep(&input, " ") !=NULL)) {
k++;
}
}
numExperiment++;
} while (strcmp(input, endof)!=0);
return 0;
}
I wrote this code and it compiles without issue but when I run it I keep getting this error:
"Segmentation Fault: 11".
What this code is supposed to do is read a file and put all data on odd lines to one array and data on even lines on 2d arrays. I'm using command line redirection to read the file.
If anyone could point me in the right direction on how to correct this, that'd be great.
EDIT 1: I made a changes suggested below regarding allocating memory and fgets but i'm still getting segmentation fault 11.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 1000
int numExperiment=1;
int main(int argc, const char * argv[])
{
char* experiments[20];
int data[10][20];
char* input=malloc(N);
char* endof="***END***\n";
do {
if (fgets(input, N, stdin) == NULL) break;
if (numExperiment%2 != 0) {
experiments[numExperiment-1]=strdup(input);
}
else {
int k=0;
while ((data[k][numExperiment-1]=strsep(&input, " ") !=NULL)) {
k++;
}
}
numExperiment++;
} while ((fgets(input, N, stdin) != NULL) && (strcmp(input, endof)!=0));
free(input);
return 0;
}
No allocated memory @amdixon
// char* input;
#define N 1000
char* input = malloc(N);
do {
...
} while (strcmp(input, endof)!=0);
free(input);
Bad use of fgets()
do {
// input=fgets(input, 20, stdin);
if (fgets(input, N, stdin) == NULL) break;
...
} while (strcmp(input, endof)!=0);
Likely wrong endof
string.
// char* endof="***END***";
char* endof = "***END***\n"; // Add \n for `fgets()`
Suggest do while
re-write
while (fgets(input, N, stdin) != NULL) && strcmp(input, endof)!=0) {
...
}
char* input;
input=fgets(input, 20, stdin);
You have declared input
, but not allocated memory for it.
Do either
char input[20];
or
char * input;
input = malloc(20);
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.