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

Re: [OT] C programming, variable size array



On Friday 12 December 2003 11:38 am, 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".

Hmmm... sounds a lot like a homework problem... =)

Of course, the normal way to do something like this is to not use C, 
since it's way more low-level than you need. 

I'd use Ruby:

numbers = []
while line = gets
  numbers << line.to_i
end

It's similarly simple in Perl, Python, etc.

But I'm guessing that you want to do it in C for *some* reason:

> #include <stdio.h>
>
> main()
> {
> int tmp, cnt = 0;
> static int arr[cnt];
> printf( "Enter Number\n");
> scanf( "%d", &tmp);
> while ( (tmp = getchar() ) != EOF ) {
>         arr[cnt] = tmp;
>         cnt += 1;
>         static int arr[cnt];
>         printf( "Enter Number\n");
>         scanf( "%d", &tmp);
> }
>
> return 0;
> }

There are a number of problems with this code, but here is a biggie: you 
are declaring 'arr' as static; this means that the storage for 'arr' 
has to be initialized during compilation, which in this case is of 
course impossible, since 'cnt' is dynamic. Of course, just getting rid 
of the 'static' isn't going to make this work either.

If you want a dynamically sized array in C, you'll need to allocate it 
using malloc() and friends ('man malloc' for more info). It's not 
efficient, but you could 'realloc()' the memory every time. 

Something like this would work if you fill in some of the blanks:

int main() {
  int *array = malloc(sizeof(int));
  int size = 0;
  printf("Enter Number\n");
  while (/*not EOF*/) {
    size += sizeof(int);
    array = realloc(array, size);
    scanf("%d", &array[size/sizeof(int)-1]);
  }
}

It would be better to allocate memory in chunks, or better yet, do 
something like read the numbers into a linked-list and then copy them 
to an array when you're ready to use them that way, or to use C++ and 
use the <vector> class, or something like that.

-- 
Wesley J. Landaker - wjl@icecavern.net
OpenPGP FP: 4135 2A3B 4726 ACC5 9094  0097 F0A9 8A4C 4CD6 E3D2

Attachment: pgpoo4eibkMvF.pgp
Description: signature


Reply to: