[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[linuxiran] [OT] C programming, variable size array
From: |
Aryan Ameri |
Subject: |
[linuxiran] [OT] C programming, variable size array |
Date: |
Fri, 12 Dec 2003 20:40:11 +0200 |
User-agent: |
KMail/1.5.3 |
Hi There:
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];
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!
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