[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".
> 
> Which seems pretty simple in first glance, but has one problem. When 
> initializing the array, I don't know it's size (and I don't want to ask 
> the user to enter it's size). The first soloution that came to my mind 
> was to initialize the array to a very big number. However this is not 
> elegant programming, and is a waste of memory. My second soloution was, 
> to initialize the array inside the loop, so that it enlarges it's size 
> continously each time the user inputs a number. I wrote the following 
> code:
> 
> #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];
	  ^^^^^^^^^^^^^^^^^^^^
	  can't do this !

>         printf( "Enter Number\n");
>         scanf( "%d", &tmp);
> }
> 
> return 0;
> }
> 
> This sounded logical to me. But the compiler (gcc 3.2) gives me a syntax 
> error saying that 'storage size of 'arr' isn't constant'. Well, I don't 
> want it to be constant!
> 

This is a big no no
Read about the difference between the stack and heap.
Local variable are allocated on the stack which is in general setup on
function call (the generally is because you can use alloca to allocate
space on the stack).
Basically what you want is dynamic allocation (malloc) and then resize
using either a new malloc and memcopy or realloc (double the size of
the array each time) or using linked lists.

> I was wondering if any of you could help me solve this question. This is 
> not yet-another-student-asking-for-help-to-do-homework. This is a 
> problem for me, which has made me busy for a couple of days, and 
> googling and greping /usr/include and other basic methods didn't reveal 
> anything to me.
> 
> PS: Now that I am on the subject, can anyone point me to a active C 
> mailing list? one that I can ask these kind of question from, as they 
> come up? preferrably with a tendency towards Unix/Linux. (mailing lists 
> please, not newsgroups).
> 
> 
> Cheers
> -- 
> /*  Trademarks, Copyrights, Patents, etc are all loans from the public 
> domain. They are not a property ('intellectual' or otherwise.) */
> 	
> 
> Aryan Ameri
> 
> 
> -- 
> To UNSUBSCRIBE, email to debian-user-request@lists.debian.org 
> with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
> 



Reply to: