Re: [OT] C programming, variable size array
On Friday 12 December 2003 22:04, Wesley J Landaker wrote:
> On Friday 12 December 2003 11:38 am, Aryan Ameri wrote:
> > #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]);
> }
> }
About initializing the array as static, well I thought that way, when I
reinitialize it, I would be able to save it's contents (if you know
what I mean). I was afraid that if it was a automatic array, when I
re-initialize it, it's contents would be gone.
Well, apparently I was wrong. Yes, I just studied pointers, but I didn't
know of malloc and realoc functoins. The man pages are now putting me
in the right direction.
> 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.
About initializing the array as static, well I thought that way, when I
reinitialize it, I would be able to save it's contents (if you know
what I mean). I was afraid that if it was a automatic array, when I
re-initialize it, it's contents would be gone.
Well, apparently I was wrong. Yes, I just studied pointers, but I didn't
know of malloc and realoc functoins. The man pages are now putting me
in the right direction. Thanks for helping.
I should also go and see what is a linked-list :-D
And no, it was not a homework. Our instructor wouldn't have given this
to us, while we haven't learned malloc and realoc yet. It was just
something that I was curius about.
Thanks very much for the tips.
Cheers
--
/* Trademarks, Copyrights, Patents, etc are all loans from the public
domain. They are not a property ('intellectual' or otherwise.) */
Aryan Ameri
Reply to: