Question about reading strings from file
It appears that when you enter command line arguments or use fgets() to input a string you can assign that string to another string variable using the assignment operator. But when you read from a file, you can't do that, you get a segfault. It seems the only way to get around that is to malloc the string and use the strcpy function. Can anyone explain?
Code:
#include <stdio.h>
struct person {
char *names[2];
};
void readFile(struct person p){
FILE *file = fopen("names", "r");
int idx = 0;
char line[20];
while(fgets(line, 20, file)){
p.names[idx++] = line;
}
fclose(file);
}
int main(int argc, char *argv[]){
struct person p;
//p.names[0] = argv[1];
//p.names[1] = argv[2];
readFile(p);
printf("This is what you typed: %s %s\n", p.names[0], p.names[1]);
}