Thread: Pointer related problem

  1. #1
    Registered User
    Join Date
    Jun 2011

    Question Pointer related problem

    The following function readline() is used to read the lines from console and store the pointers to each line into the *lineptr[MAXLINES].

    #define MAXLINES 5000
    #define MAXLEN    1000
    int getline(char *line, int maxlen);
    int readlines(char *lineptr[], int maxlines);
    char *lineptr[MAXLINES];
    int readlines(char *lineptr[], int maxlines)
      int len, nlines;
      char *p, line[MAXLEN];
      while((len=getline(line, MAXLEN)>0)
         if(nlines>=maxlines ||(p=(char *)malloc(len))==NULL)
           return -1;
           lines[len-1]='\0';/*delete newline*/
           strcpy(p, line);
         return nlines;
    How can we write this function using only the *lineptr[] but not using the malloc to maintain storage?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Well the memory has to be allocated somewhere.
    If this function doesn't then either
    - getline returns a block of memory for each line read
    - main fills the array before calling readlines

    Or you just use large arrays somewhere.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    You could use a fixed length array of strings, which is just a char matrix.
    char lineptr[MAXLINES][MAXLEN] = { "", "example foo", "example bar" };
    You're free to do whatever you like initialization wise: I just wanted to demonstrate the workings of the data structure.

    You will have to change the type of the lineptr parameter for this to work and reduce the memory request. 5000 lines * 1000 bytes is 4.7 megabytes, which is too big for the stack, generally.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Widget problem [GTK RELATED]
    By darekg11 in forum C Programming
    Replies: 5
    Last Post: 05-09-2011, 12:25 PM
  2. pointer related: can't figure out this bug
    By dayalsoap in forum C Programming
    Replies: 7
    Last Post: 10-18-2010, 08:08 PM
  3. A problem related to DB and C using SQLAPI++
    By redhunter in forum C Programming
    Replies: 0
    Last Post: 05-12-2004, 10:14 AM
  4. memory question (pointer related)
    By cjschw in forum C++ Programming
    Replies: 2
    Last Post: 04-30-2004, 01:09 PM
  5. Class related problem
    By Gnoober in forum C++ Programming
    Replies: 3
    Last Post: 10-07-2002, 10:11 PM