[C++] Arrays

In C#, you do not use arrays often. In many cases you use Collections and Generics. In C++, you can use STL but in many cases, you are likely to use arrays.


1. Arrays

In .Net programming, you use collections rather than arrays in most cases. In C++, you will use “Standard Template Libraries” instead of arrays. But arrays can be useful in some simple cases. In C++, arrays and pointers are interchangeable. So be aware of the potential danger of misuse of an array.


2 Declaration / Initialization

type arr_name[size];
type arr_name[] = {val1, val2, ... };
type* arr_name = new type[size]; // should be deleted


3. Getting the Length of an Array

Unlike C#, C++ does not provideĀ an easy way to determine the size of an array. But you can use the “sizeof” operator.

int iArr[] = {1,2,3,4};
int size = sizeof(iArr)/sizeof(int);
cout << "size = " << size << endl; // 4


int* iArr = new int[10];
int total = 0;
for(int i=0; i<10; i++)
  iArr[i] = i+1;
for(int i=0; i<10; i++)
  total += iArr[i];
cout << "Total = " << total << endl; // 55
delete iArr;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s