[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C programming, variable size array



On Fri, Dec 12, 2003 at 08:38:18PM +0200, Aryan Ameri wrote:
> Hi There:
> 
> I am a first year CS student, learning C. A while ago I was asked this 
> question from a fellow friend of mine:
> 
> "Write a program, which promts the uset to enter some numbers. The user 
> should terminate the sequence of numbers by entering EOF character. The 
> program should put numbers entered by the user in to a 1D array".

Does the code have to be clean ? If not, you can solve this recursively,
assuming knowledge of only a little bit of undefined behaviour by the
compiler, and infinite stackspace, but that shouldn't be a problem, right ?

It doen't use an array though, and making a true linked list solution
based on the same principles is left as an exercise to the reader.

void readNum(int *prevNum,int *firstNum)
{
   int thisNum,nrRead;
   int *num=prevNum;

   printf( "Enter Number\n");
   nrRead=scanf( "%d", &thisNum);
   if(nrRead==1)
   {
      readNum(&thisNum,prevNum==0?&thisNum:firstNum);
   }
   else
   {
      do
      {
         printf("%d\n",*num);
         num-=(&thisNum-prevNum);
      }
      while(num<=firstNum);
   }
}

main()
{
   readNum(0,0);
}

If you don't like recursion, you have to use an array, stack space is
limited, undefined behaviour is not wanted, or you don't like malloc and
realloc, you might try the following:

#include <unistd.h>
#include <signal.h>

int *array;

void sighandler(int sig)
{
   sbrk(sizeof(int));
}

main()
{
   int i=0,j;
   int nrRead;
   array=sbrk(0);
   signal(11,sighandler);
   do
   {
      printf( "Enter Number\n");
      nrRead=scanf( "%d", &array[i]);
      i++;
   }
   while(nrRead==1);
   for(j=0;j<i-1;j++)
   {
      printf("%d ",array[j]);
   }
   printf("\n");
}

Frank

-- 
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it." - Brian W. Kernighan



Reply to: