Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

C - How can I copy one string into an element of character arrays?

I'm trying to parse a file and have an array of character pointers whose length is the number of lines in the file. I want to copy each line into an element of this array, but keep getting a segmentation fault. I don't see what I'm doing wrong, so if anybody could help it would be greatly appreciated. Here is my code.

char * unsplitLines[numLines];
char line[20];
int i;
for(i = 0; i < lines; i++)
{
    fgets(line, 20, fp);
    //printf("%s
", line);
    unsplitLines[i] = line;
}

The gets function works fine, but the assignment after it causes the segmentation fault.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

fgets do not allocate buffer for you, so all the elements in unsplitLines store same pointer line and its content is the end line of file.

try asprintf

char * unsplitLines[numLines];
char line[20];
int i;
for(i = 0; i < lines; i++)
{
    fgets(line, 20, fp);
    asprintf(unsplitLines[i], "%s", line);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...