String-length of an multi-dimensional array

This is a discussion on String-length of an multi-dimensional array within the C Programming forums, part of the General Programming Boards category; Fixed: Code: char **ftoarray(FILE *file) { size_t size, lines; char **array, *whole, *delim; fseek(file, 0, SEEK_SET); fseek(file, 0, SEEK_END); size ...

  1. #16
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Fixed:
    Code:
    char **ftoarray(FILE *file)
    {
      size_t size, lines;
      char **array, *whole, *delim;
    
      fseek(file, 0, SEEK_SET);
      fseek(file, 0, SEEK_END);
      size = ftell(file)+1;
      fseek(file, 0, SEEK_SET);
    
      if(!(whole = malloc(size)))
        return NULL;
    
      whole[size-1] = '\0';
    
      if(fread(whole, 1, size-1, file) != size)
      {
        free(whole);
        return NULL;
      }
      
      for(lines = 0, delim = strtok(whole, "\n"); delim; delim = strtok(NULL, "\n"))
        ++lines;
    
      if(!(array = malloc((lines+1) * sizeof(*array) + size)))
      {
        free(whole);
        return NULL;
      }
    
      array[lines] = NULL; /* NULL terminator */
      memcpy(array + lines + 1, whole, size);
      free(whole);
    
      for(size = 0, delim = array[lines + 1]; *delim; delim += strlen(delim) + 1, ++size)
        array[size] = delim;
    
      return array;
    }
    Last edited by master5001; 10-30-2008 at 03:21 PM.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem within multi dimensional array
    By lolguy in forum C Programming
    Replies: 5
    Last Post: 12-26-2008, 07:02 AM
  2. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  3. string into 2 dimensional array - basic stuff
    By mellisa in forum C++ Programming
    Replies: 11
    Last Post: 01-18-2003, 02:08 AM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. length of string etc.
    By Peachy in forum C Programming
    Replies: 5
    Last Post: 09-27-2001, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21