Emuforums.com

Go Back   Emuforums.com > General Discussion > Web development / Programming
About Us Register FAQ Members List Calendar Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
Old September 22nd, 2003   #1 (permalink)
General of Tangerines
 
RZetlin's Avatar
 
Join Date: Jun 2001
Location: Defending the Sea
Posts: 3,885
Question C: Setting the size of array during runtime

Is there a way to set the size of the array during runtime?

void main(void)
{
int master_size;
printf("Please enter the size of the master array");
scanf("%i",&master_size);
char master_array[master_size];
}

I get an error when I try to compile in Borland 5.5.

Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
Assign1.cpp:
Error E2313 Assign1.cpp 8: Constant expression required in function main()

But it seems to run okay in Dev C++ 4.
__________________


AMD Athlon 64 3700+ | 2 GB RAM | XFX Nvidia 6800 GS 256 MB XXX Edition | Win XP Pro SP2
RZetlin is offline   Reply With Quote
Old September 22nd, 2003   #2 (permalink)
Registered User
 
Join Date: Jul 2003
Location: Los Angeles
Posts: 53
Re: C: Setting the size of array during runtime

Yes, but not with that method.

This is because, with C/C++ and most programming languages, the memory is allocated when the exe is run - that is, not at the time it's needed.

It's better to use new in C++. I think malloc can also be used in C, I'm not sure. And, I'm not sure why it works with Dev-C++, it might be using new just because it seems like you want it.

-[Unknown]
[Unknown] is offline   Reply With Quote
Old September 22nd, 2003   #3 (permalink)
Knowledge is the solution
 
Proto's Avatar
 
Join Date: Dec 2002
Location: Mexico City, Mexico
Posts: 5,570
Re: C: Setting the size of array during runtime

yeah.. first declare a global array as a pointer like
char *master_array;

then when you obtain a given size use *master_array = new char[x]

Dont forget to use delete master_array; within the destroyer or at the end of the program, so you free the memory
__________________


Proto is offline   Reply With Quote
Old September 22nd, 2003   #4 (permalink)
Emu author
 
zenogais's Avatar
 
Join Date: Aug 2003
Location: Victorville(Near Los Angeles or LA for those who are on the DL)
Posts: 839
Re: C: Setting the size of array during runtime

Here's my source code for doing this. Although I don't see any reason why you would ever need a program to do this and it isn't very safe, here it is:

Code:
C++:

#include iostream
using namespace std;

int main() {
	int array_size = 0;
	cout<<"Enter the size of the array: ";
	cin >> array_size;
	int* my_array = new int[array_size];
	delete[] my_array;
	return 0;
}
Code:
C:

#include stdio.h
#include malloc.h

int main() {
	int array_size = 0;
	printf("Enter array size: ");
	scanf("%i", &array_size);
	int* my_array = (int*)malloc(array_size);
	free((void*)my_array);
	return 0;
}
Try to use the C++ functions new and delete instead of malloc and free because they are much safer and they work exactly the same. Also your implementation is impossible because doing "int my_array[array_size];" Tells the compiler that your creating an array of array_size, and the compiler assumes that the size of the array is known at compile time, but if array_size is not known till runtime then it just won't compile because how can you create an array of size x if you don't know what x is?
__________________
-----------------
Emu Tinkerer and C++ Programmer

Last edited by zenogais; September 22nd, 2003 at 05:33.
zenogais is offline   Reply With Quote
Old September 22nd, 2003   #5 (permalink)
Emu author
 
ammoQ's Avatar
 
Join Date: Mar 2002
Location: Vienna/Austria/Europe
Posts: 1,168
Re: C: Setting the size of array during runtime

The C program has a bad bug: the array is actually smaller than expected; you forgot to multiply with sizeof(int).

The correct code:
<code>
...
int* my_array = (int *)malloc(array_size*sizeof(int));
...
</code>
__________________
If you think my English is bad, wait till you read my Polish.
ammoQ is offline   Reply With Quote
Old September 23rd, 2003   #6 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Setting the size of array during runtime

Here's how to use dynamic sized strings at runtime (since you're using C++, look into the string class that is now part of the new C++ standard).

Code:
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main()
{
        int i=0, length;
        char ch;
        char *s; /* s is a pointer to some random memory address */
        /* To use it, we must allocate memory. */
        char *si;

        s = malloc(sizeof(char)*50);
        /* s now points to some memory we can use (50 char's). */

        /* *s is used to access the first char, *(s+offset) is used to
         * access the other char's.
         * s[offset] is the same as *(s+offset)
         */

        /* The following loop populates are memory with characters from
         * input. Only 49 characters are input, with the 50th element
         * set to the '\0' NUL char. */

        while ((ch = fgetc(stdin)) != '\n') {
                if (i<49) 
                        s[i++] = ch;
        }
        s[i] = '\0';

        printf("%s\n", s);

        /* We can also iterate through the array and check its length.
         * '\0' evaluates as false, so this works. */
        for (i=0; s[i]; i++);

        /* i is now equal to the length of our string, minus the NUL
         * char. This makes it 49. */

        length = i;
        printf("%d\n", length);

        /* You can also use pointer arithmetic to come up with the same
         * value. We copy our pointer so we don't loose the address of
         * the first element. */
        for (si=s; *si; si++);
        length = si-s;

        printf("%d\n", length);

        free(s); /* Free our memory. */

        /* Keep in mind this is C code. If you use C++, don't mix the
         * new and delete keywords with malloc and free, or bad things
         * will happen. I've also left out the use of realloc in this
         * example, but look it up and see what you can come up with. */
        
        return 0;
}
Also, NEVER use "void" main. main should always have a return type of int.

Also, arrays are just pointers to their first element, so you can access them in the same manner *(array+offset), since the C compiler just does that when you use array[offset] notation anyway.

Keep in mind that unless the array is declared static, it will be created on the stack and won't exist once it goes out of scope.

However, malloc'ed memory is created on the heap and won't go away until free'd. This applies to new'd and delete'd memory as well. You have to use pointers to store the addresses of allocated memory to use and free it.

Trying to free a pointer to memory that hasn't been allocated (or has already been free'd) will cause undefined behavior. Avoid this by initializing pointers to NULL and setting them to NULL after freeing them. This way, only pointers that have been malloc'ed are non-NULL. Freeing a NULL pointer does nothing and is safe. NULL is declared in stdlib.h. You can also use 0.

Quote:
Originally Posted by [Unknown]
Yes, but not with that method.

This is because, with C/C++ and most programming languages, the memory is allocated when the exe is run - that is, not at the time it's needed.

It's better to use new in C++. I think malloc can also be used in C, I'm not sure. And, I'm not sure why it works with Dev-C++, it might be using new just because it seems like you want it.

-[Unknown]
malloc is a standard C library function defined in stdlib.h (cstdlib in C++). As long as you don't mix malloc and free with new and delete, you shouldn't have any problems.

Also, C99 is the new 1999 ISO standard for C. It supports the creation of variable-size arrays at runtime. I believe GCC3 (which is what Dev-C++ uses) has partial support for this already.

However, C99 is only beginning to be implemented and relying on its features isn't very wise at this time. It's better to fall back on pure C89 code or the new ISO C++.
RamsusX is offline   Reply With Quote
Old September 23rd, 2003   #7 (permalink)
Emu author
 
zenogais's Avatar
 
Join Date: Aug 2003
Location: Victorville(Near Los Angeles or LA for those who are on the DL)
Posts: 839
Re: C: Setting the size of array during runtime

Quote:
Originally Posted by ammoQ
The C program has a bad bug: the array is actually smaller than expected; you forgot to multiply with sizeof(int).

The correct code:
<code>
...
int* my_array = (int *)malloc(array_size*sizeof(int));
...
</code>
Sorry 'bout that not much of a C programmer.

Also just a note. The only time I use malloc/free with C++ is when I'm defining my own operator new/delete;
__________________
-----------------
Emu Tinkerer and C++ Programmer

Last edited by zenogais; September 23rd, 2003 at 18:29.
zenogais is offline   Reply With Quote
Old September 23rd, 2003   #8 (permalink)
Emu author
 
ammoQ's Avatar
 
Join Date: Mar 2002
Location: Vienna/Austria/Europe
Posts: 1,168
Re: C: Setting the size of array during runtime

I aggree that you should not use malloc/free with C++, for it is a crude tool like so many constructs in C.
__________________
If you think my English is bad, wait till you read my Polish.
ammoQ is offline   Reply With Quote
Old September 25th, 2003   #9 (permalink)
/dev/user
 
Ipswitch's Avatar
 
Join Date: Nov 2002
Location: Internet
Posts: 407
Re: C: Setting the size of array during runtime

another, maybe even better, way of changing the size with one line is realloc.
Code:
char* array = (char*)malloc(sizeof(char)*number_of_elems);
int newsize = blah;
realloc(array, sizeof(char)*newsize);
Ipswitch is offline   Reply With Quote
Old September 25th, 2003   #10 (permalink)
Emu author
 
ammoQ's Avatar
 
Join Date: Mar 2002
Location: Vienna/Austria/Europe
Posts: 1,168
Re: C: Setting the size of array during runtime

very important:
<code>
<b>array=</b>realloc(array, sizeof(char)*newsize);
</code>
because the memory block can be moved by realloc!
__________________
If you think my English is bad, wait till you read my Polish.
ammoQ is offline   Reply With Quote
Old September 26th, 2003   #11 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Setting the size of array during runtime

Something no one mentioned (probably because most people aren't aware of this) is that C99, the latest ANSI C standard, does in fact allow for variably sized arrays. This is why DevC++ supports them; DevC++ uses mingw, which is a variant of GCC, which has at least tried to support C99 correctly (and is constantly adding more support. At GCC 3.3 they've come a pretty long way). On the other hand, it seems commercial compilers don't care very much about this new standard.

An alternative to using dynamically sized arrays is to use alloca. This will still allocate the array on the stack, just like a normal array, so you won't have to deallocate it, but it'll be invalid after the function returns. alloca has the same syntax as malloc, but chances are the popular venders also don't support it, either.

EDIT: Rawr, I didn't notice that RamsusX DID in fact mention C99 and variable arrays there. Sorry :\

- Exo

Last edited by Exophase; September 26th, 2003 at 21:08.
Exophase is offline   Reply With Quote
Old September 26th, 2003   #12 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Setting the size of array during runtime

Quote:
Originally Posted by ammoQ
The C program has a bad bug: the array is actually smaller than expected; you forgot to multiply with sizeof(int).

The correct code:
<code>
...
int* my_array = (int *)malloc(array_size*sizeof(int));
...
</code>
That's not a bug, that's an error on the programmer's part. malloc is byte-wise for purposes of greater control at the expensive of programming ease.

- Exo
Exophase is offline   Reply With Quote
Old September 27th, 2003   #13 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Setting the size of array during runtime

Quote:
Originally Posted by Exophase
That's not a bug, that's an error on the programmer's part. malloc is byte-wise for purposes of greater control at the expensive of programming ease.

- Exo
ammoQ meant that the original code the person had posted had a bug in it, not malloc.
RamsusX is offline   Reply With Quote
Old September 28th, 2003   #14 (permalink)
Emu author
 
ammoQ's Avatar
 
Join Date: Mar 2002
Location: Vienna/Austria/Europe
Posts: 1,168
Re: C: Setting the size of array during runtime

Thanks, RamsusX, you got it right. (Althoug I think the C language has some "bugs" in it... gets() - 'nough said)
__________________
If you think my English is bad, wait till you read my Polish.
ammoQ is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 07:20.

© 2006 - 2008 Emu Forums | About Emu Forums | Legal | A member of the Crowdgather Forum Community


Powered by vBulletin® Version 3.7.0 Release Candidate 3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0 RC5