Search code examples
cmallocstrdup

Using strdup into malloc reserved space


I've never used malloc to store more than values but I have to use strdup to order the lines of an input file and I dont get a way to make it work.

I though using strdup() to get a pointer to each line and later, put each one into a space according to the number of lines reserved with malloc().

I dont know if I have to do it like reserved memory was an array to pointers, I mean using char** and later put each pointer to each strdup into reserved space.

I though something like this:

char **buffer;
char *pointertostring;
char *line; // line got using fgets

*buffer = (char*)malloc(sizeof(char*));
pointertostring = strdup(line);

I don't know what to do after that, I don't even know if this is correct, in that case, what should I do to store the pointer to the string in a position of buffer?

Regards


Solution

  • If I understand your requirement correctly. You'll have to do something like:

    char **buffer; 
    char line[MAX_LINE_LEN]; // line got using fgets
    int count; // to keep track of line number.    
    
    // allocate one char pointer for each line in the file.
    buffer = (char**)malloc(sizeof(char*) * MAX_LINES); 
    
    count = 0; // initilize count.
    
    // iterate till there are lines in the file...read the line using fgets.
    while(fgets(line,MAX_LINE_LEN,stdin)) {
        // copy the line using strdup and make the buffer pointer number 'count' 
        // point to it
        buffer[count++] = strdup(line);
    }
    ....
    ....
    // once done using the memory you need to free it.
    for(count=0;count<MAX_LINES;count++) {
         free(buffer[count]);
    }
    ....
    ....