[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CArray
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CArray
(C) Array
A way to store a a large number of values and access them by index. There are two kinds of arrays:- Static arrays (size known at compile-time)
- Dynamically allocated arrays (size known at run-time)
Static arrays
int main() { /* Create an array */ int i = 0; int array[ARRAY_SIZE]; /* Initialize it with non-random values */ for (i=0; i!=ARRAY_SIZE; i++) array[i]=i /* Square them */ for (i=0; i!=ARRAY_SIZE; i++) array[i]*=i /* sprintf them */ /* TODO: sprintf them */ return 0; }
- define ARRAY_SIZE = 10
How to determine a static array's size?
This can be done from the array's pointer and the size of the zero-th element:
- include <assert.h>
int main() { int myArray[ARRAY_SIZE]; const int size = (sizeof(myArray)/sizeof(myArray[0])); assert(size==ARRAY_SIZE); return 0; }
- define ARRAY_SIZE = 10
Dynamically allocated arrays
These array's sizes are unknown at ?compile-time and use malloc and ?free.int main() { /* TODO: Convert this to C const int randomSize = std::rand()%100; int * myArray = new int[randomSize]; delete[] myArray;
- include <stdio.h>
- include <assert.h>
- /
How to determine a dynamically allocated array's size?
This can NOT[/red] be done from the array's pointer and the size of the zero-th element:int main() { int randomSize = 2 + rand()%100; /* Can never be 1 */ /* TODO: Convert this to C int * myArray = new int[randomSize]; const int size = (sizeof(myArray)/sizeof(myArray[0])); std::cout << "randomSize: " << randomSize << std::endl; std::cout << "size: " << size << std::endl; assert(size==1); assert(size!=randomSize); delete[] myArray;
- include <stdlib.h>
- include <assert.h>
- /
'Array' links
Code links
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
