View Single Post
Old 08-11-2004, 01:31 AM   #2 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,736
redhead is on a distinguished road
Look at dynamical memory allocation malloc() or alloca() ie:
Code:
#include <stdio.h>
#include <stdlib.h>

typedef struct my_array {
      char letter;
      struct my_array* next;
      struct my_array* prev;
} my_array;


int main()
{
  FILE* file;
  my_array* cur;
  my_array* next;
  /* allocate room for atleast one array member */
  cur = (my_array*) alloca(sizeof(my_array));
  cur->prev = NULL;
  cur->next = NULL;
  file = fopen("my_file", "r");
  while(!feof(file))
  {
    if(EOF != cur->letter = fgetc(file))
    {
      /* since we could read something 
       * we need to allocate room for one more letter 
       */
      next = (my_array*) alloca( sizeof(my_array));
      /* alter cur to point at active member in array */
      cur->next = next;
      next->prev = cur;
      next->next = NULL;
      cur = cur->next;
      cur->letter = '\0';
    }
  }
  fclose(file);
  while (cur != NULL)
  { /* NOTE printing in reverse order */
     printf("%c\n", cur->letter);
     cur = cur->prev;
     free (cur->next);
  }
  return 0;
}
It's a very simple run through a dynamicaly allocated array, I use alloca() instead of malloc(), since it is more safe when dealing with memory allocation, only drawback is, it dosn't work on every system.
The program hasn't been tested, and theres virtualy no error checking, but it should give you an idear.
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote