[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
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)
Take care not to write beyond the bounds of an array.

Static arrays

  1. define ARRAY_SIZE = 10
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; }


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:
  1. include <assert.h>
  1. define ARRAY_SIZE = 10
int main() { int myArray[ARRAY_SIZE]; const int size = (sizeof(myArray)/sizeof(myArray[0])); assert(size==ARRAY_SIZE); return 0; }


Dynamically allocated arrays

These array's sizes are unknown at  ?compile-time and use malloc and  ?free.
  1. include <stdio.h>
  2. include <assert.h>
int main() { /* TODO: Convert this to C const int randomSize = std::rand()%100; int * myArray = new int[randomSize]; delete[] myArray;
      • /
return 0; }


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:

  1. include <stdlib.h>
  2. include <assert.h>
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;
      • /
return 0; }


'Array' links

Code links



last edited (November 11, 2006) by bilderbikkel, Number of views: 1733, Current Rev: 2 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.