I'm a noob so I'll make this short. Is the following legal (C99)? I don't want to store more than the one array at a time. I could make an array that is of maximum needed length and use only part of it, but I'd rather do this.
int main(){
double drm[15000];
//do some stuff
double drm[14000];
//do some other stuff
}
No, you can't do that. They need to be in different blocks. You could do:
int main(void)
{
{
double drm[15000];
// do some stuff
}
{
double drm[14000];
// do some other stuff
}
}
But why not just call a function? Even if you put them in different blocks, you don't really have any guarantees about what the compiler is going to do vis-a-vis storage.
{
and ends where ever the matching }
occurs - Carl Norum 2012-04-04 20:43
As arrays are strongly related to pointers in C, you could work with dynamic arrays as well. First, allocate a new double array with 15 000 elements. When you don't need it anymore, delete it. Create a new array with 14 000 elements then.
Don't forget to free your heap after using your arrays. People tend to forget this. Moreover, you should check whether the allocation was successful.
int main(void)
{
double *drm = 0;
drm = (double*)malloc(15000 * sizeof(double));
// do something
free(drm);
drm = (double*)malloc(14000 * sizeof(double));
// do some other stuff
free(drm); // don't forget me
}
However, I would agree with Carl Norum: use functions instead.
C99
, not C++
. Please update your example to use malloc()
and free()
- tomlogic 2012-04-04 18:28
malloc
call is better written as drm = malloc(15000 * sizeof *drm);
Keith Thompson 2012-04-04 19:04
malloc()
succeeded. - Keith Thompson 2012-04-04 19:09
You could use malloc
and free
(or realloc
if you don't mind keeping the data):
#include <stdlib.h>
int main(void)
{
double *drm = (double *)malloc(sizeof(double)*15000);
//do stuff
free(drm);
drm = (double *)malloc(sizeof(double)*14000);
//do other stuff
free(drm);
}
void*
may be implicitly converted to any pointer type (other than a pointer-to-function type). The cast is just clutter, and depending on the circumstances it can mask errors. For example, in C90 if you forget the #include <stdlib.h>
(not <malloc.h>
; that's non-standard), the compiler will assume that malloc
returns int
; casting the result to double*
can cause incorrect code to be generated - Keith Thompson 2012-04-04 19:06
stdlib.h
, compiler assumes a return type of type of int and we, inadvertently will be casting it to some pointer which is still incorrect. In fact is this case compiler can generate a "cant convert from int to some*" erro - Pavan Manjunath 2012-04-04 19:14
something
to something*
conversion! Ahh, I always run C programs with a CPP compiler. My bad : - Pavan Manjunath 2012-04-04 19:24