arrays - How do I store a line in a dynamic double pointer in C -


im working on project , need know how store line read file dynamic double pointer. example assume have struct:

typedef struct {  char **data; /*dynamic array of lines */ size_t nused; /*number of lines in dynamic array */ } lines_t;  

and in readline function:

lines_t readline() {      lines_t line_data;     char line[linesize];      char *data;      line_data.data = malloc(sizeof(char *)*sizeof(line));     line_data.nused = 1;     while(fgets(line,linesize,fp)) {        data = line;         line_data.data = &data;          nalloc++;       }      printf("%s",*line_data.data);      return line_data;  }   

but print last line in file, how can make can access , print line in file?(i think may have index double pointer)

if system has it, use posix getline. you'll need duplicate gotten line using strdup, @ least if call getline in loop same arguments.

notice andré fratelli's answer limiting line size linesize getline don't have such limitation (and read wide lines of many thousand characters). of course fail if used malloc failing.

see this related question.

on gnu systems linux might want use gnu readline library, if reading terminal. adds editing abilities (and enables auto-completion).

hence readline name confusing. might add comment telling not gnu readline library, or change name else, read_a_line ....

btw, you'll better grow & allocate vector once in while, using newsize = 3*oldsize/2 + 50; geometric progression. need keep both allocated , used sizes:

typedef struct {     char **data; /*dynamic array of nallocated lines */    size_t nallocated; // allocated size of `data` above    size_t nused; // count of used lines in dynamic array    /// invariant: nused <= nallocated } lines_t;  

at last, don't forget test malloc (& calloc & realloc) , fgets or getline or readline against failure. on linux, use ulimit in shell, calls setrlimit(2) (you want rlimit_as), stress test against malloc failure.


Comments