Hello. I am new to C and have a simple question.
If I had something like this:
Would the computer know that the array should hold 5 integers, even though I calculated x afterwards?Code:int x; int array[x]; x = 5;
Thanks in advance!
Hello. I am new to C and have a simple question.
If I had something like this:
Would the computer know that the array should hold 5 integers, even though I calculated x afterwards?Code:int x; int array[x]; x = 5;
Thanks in advance!
In a word, no.
I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo
Definitely not. Nor would this work:
Declaring an array like that is a static array, therefore the compiler looks at the size specified at compile time and allocates storage. Since the value of x is not determined until run time the compiler does not know how many bytes of memory to allocate to the array.Code:int x; x = 5; int array[x];
Declaring an array like this is a dynamic array, therefore at run time the size of the array is determined and since it's at run time the value of x is determined therefore allocating 'x' * 4 bytes of memory is acceptable.Code:int x; x = 5; int * array; array = new int[x]; delete [] array;
Just a side note, the memory must be released for a dynamic array using delete.
Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
Haha my bad
Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
So would this work? And is this the correct syntax for malloc/free?
Thanks everyone.Code:int x; int * array; x = 5; array = malloc(int[x]); // ...code free(array);
Close. malloc wants the number of bytes to allocate. If you want 5 integers, then you need the size of an integer. Commonly done like so:Or, if you prefer:Code:int *foo; int x = 5; foo = malloc( x * sizeof( int ) );Code:foo = malloc( x * sizeof( *foo ) );
Quzah.
Hope is the first step on the road to disappointment.
Thanks! It works, but on the following line:
Dashcode is giving me the following warning:Code:free(array);
"Implicit declaration of function 'free'"
What does this mean?
Code:#include<stdlib.h>
Quzah.
Hope is the first step on the road to disappointment.
Awesome. Thanks everyone!