hi. do i have to always allocate memory when i use arrays? for instance, i need to use an array of ints where length is a variable. i wrote "int a[n];" should i change it to "int a[n] = malloc(sizeof(int)*n);"?
hi. do i have to always allocate memory when i use arrays? for instance, i need to use an array of ints where length is a variable. i wrote "int a[n];" should i change it to "int a[n] = malloc(sizeof(int)*n);"?
Of course, but if you just define:Originally Posted by cAsk
where N is a constant, then memory will be allocated, but you need not worry about manually managing the memory.Code:int a[N];
If you are compiling with respect to C99, or with respect to C11 where the feature is supported, or with respect to an earlier version of C where the feature is available as a language extension, then you can use variable length arrays, e.g.,Originally Posted by cAsk
where n is not a constant. However, such an array cannot be resized during its lifetime. Furthermore, because of the caveats about compiler support, you may choose to use the two other more portable options:Code:int a[n];
- Allocate an array as large as you will ever need, then use as much as you need. Unfortunately, this may result in a colossal waste of space.
- Use dynamic memory allocation with malloc/free and related functions. This allows you to resize the dynamic array with realloc. However, you would need to declare a pointer, not an array, e.g.,
and then you should check that malloc did not return a null pointer, and remember to free.Code:int *a = malloc(sizeof(a[0]) * n);
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
thanks for the ellaborated and quick response
btw, yes i use C99
You could also use
Int *a = malloc(sizeof(*a) * n);