Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
Dec

C++ Basics Tutorial - Lesson 4

Related Blog Items

Please refer lesson 3

4. Arrays
4.1 Declare and Initialize Array
4.2 Array Size Must Be Constant
4.3 Array Size
4.4 Array and Pointer
4.5 Pass Array to Function
4.6 Searching Array
4.7 Multiple-Subscripted Array
4.8 String Handling Functions

4. Arrays

4.1 Declare and Initialize Array

To initialize the array when declaring:

int x, y, student[5] = {0, 1, 4, 9, 16};

The numbers in {} are called initializers. If the number of initializers are less than the number of the array elements, the remaining elements are automatically initialized to zero. There must be at least one initializer in the {}. But such kind of expression can only be used in declaration. You can’t use “{0, 1,..}” in assignment.

4.2 Array Size Must Be Constant

Instead of directly placing a figure such as “21″ in the braces of the array declaration, it is better to place a constant variable. In such way when you need the change the array size you only need to change one place.

const int size = 21;

The other reason is to avoid magic number : if number 21 frequently appears in the program, and an other irrelevant 21 happens to appear, it will mislead the reader that this 21 has something to do with the former one.

Only constant variable can be used as array size. Therefore you can not make the array size dynamic by inputting an integer from keyboard in run time and use it as array size.

4.3 Array Size

In Java, an array is an object with an array with fixed-size, plus data member (”length”) indicating the array size, and compiling-time boundary checking. But in C++ an array is just an address of the first array element. Declaring the size of the array can only help compiler to allocate memory for the array, but the compiler never checks whether the array bound or size is exceeded:

 
int main ()
{
   int b, a[3] = {0,1,2};
   a[3]=3;
   cout << "a[3] = " << a[3] << endl;
   a[4]=4;
   cout << "a[4] = " << a[4] <<endl;
   cin >> b;
}

The problem that will happen if you exceed the array bound is: because the compiler was told that the array was only of 3 elements, so it may have put other variables in the succeeding memory locations. Therefore by declaring an array of 3 elements then putting a value into the 4th element, you may have overwritten another variables and produced very serious logic errors which is very difficult to find out.

Therefore, the size of an array should be carefully observed.

4.4 Array and Pointer

There are two widely used formats to represent a block of data: a pointer and an array:

char * cPtr;
char buf[80];

The name of an array is a constant pointer to the first element of the array. Therefore, the name of a charcter array is equal to “const char *”. You can not assign anther address to the array name like

buf = cPtr;

The other difference between a pointer and array is: a pointer such as char * cPtr can point to anywhere, most probably somewhere in the OS’s territory that you can’t access. An array such as char buf[80] however, points to a block of memory allocated by the compiler.

If a block of characters ends with NULL i.e. 0, it can be treated as a string, which is recognized in most applications.

=>Double-quoted constant string

A double-quote enclosed string represents a const char const * pointing to some compiler-allocated space holding the string, with the last character being NULL. Therefore, when you say

char * cPtr;
cPtr = “Hello world!”;

Compiler will allocate a continuous 13 bytes (last byte to hold NULL or 0) some where, set them to be “Hello world!”, and assign its address to pointer cPtr. Because the bytes are constant, you can never amend the content of the string.

Therefore, if you want to amend the content of “Hello world!”, you can not directly assign its address to a pointer. You have to copy the constant bytes into a character array:

240b42f77387187d61f7531b5499102e002

The output will be
Hello World!

A special case is when you initialize a character array with the constant string:

char buf[80] = "Hello world!";
char buf1[] = "Hello Frank!";

Compiler will create a character array of the specified length or the length of the constant string if not specified, than fill it with the content of the constant string. You can then amend the content of the array later.

However, you can not assign a constant string to an array name after it is already created:

char buf[80];
buf = "Hello world!"; // Not allowed!

Because as said before, the array name is a constant pointer which can not be assigned.

=>Formatting character array

When you create a char array by saying
char buf[80];

every byte of it is uninitialized. So it is not a NULL-terminated string and can not be used in string manipulation functions such as strcpy, strlen, strcat, etc. To turn it into an empty but legal string:

sprintf(buf, "");
To write into a char array:
 
sprintf(buf, "%s, %.6d, %c, %.3f, 0x%.8x",
"Hello World!", 1234, 'A', 123.4, 0xaabbbb);

The output will be:
Hello World!, 001234, A, 123.400, 0×00aabbbb

For a list of all format specifications, search MSDN with title “Format Specification Fields: printf and wprintf Functions”.

4.5 Pass Array to Function

 
int calculate (int member[], int size)
{
   int i, average = 0;
 
   for( i = 0; i < size; i++)
      average += member [i];
 
   average /= size;
   return average;
} 
 
int main ( )
{
   int average, student [5] = {67, 93, 88, 89, 74};
   average = calculate (student, 5);
   cout << "The average score is " << average << endl;
   cin >> average;
   return 0;
}

To indicate to the compiler that a function is expecting an array, there must be [ ] following the array name in both the function prototype and function definition.

C++ automatically passes arrays by reference. Dereferencing operator & is not used, because the name of the array is the address of the first array element - the name of array “student” is equal to “&student[0]”.

4.6 Searching Array

There are two ways to search for a figure in an array:

Linear search: compare each array element one by one with the searched figure until it is found or reaching the end of the array. Average comparison time: half of the array size.

Binary search: can only be applied on sorted array. By checking the middle element you will find out which half of the array contains the element. Maximum comparison time: log n arraysize. If an array needs to be searched frequently, then it is worthwhile to spend a great time to sort it first. Refer to the program in 3.11 Exercise Binary Search of an Array .

4.7 Multiple-Subscripted Array

 
#include <iostream>
 
void print (int [] [3], int, int);
 
int main ( )
{
   int x;
   int array1 [2] [3] = { {1, 2, 3}, {4, 5, 6}};
   int array2 [2] [3] = {1, 2, 3, 4};
   print (array1, 2, 3);
   print (array2, 2, 3);
   cin >> x;
   return 0;
}
 
void print (int a [] [3], int first, int second)
{
   for(int i = 0; i < first; i++)
   {
      for(int j = 0; j < second; j++)
             cout << a [i] [j];
 
     cout << endl;
   }
 
  return;
}
=>Declaration of the dimensions

When passing the array to a called function, each dimension of the array should be declared in both the function prototype and function definition. The first dimension does not need a number, just like single-dimension arrays, but the subsequent dimensions does.

An n x 3 array is located in the memory in such a sequence: (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2)… If the compiler knows the number of columns which is 3, it will put the fist element (0, 0) of first row on the first memory location, the first element on second row on the fourth memory location, the first element on third row on the 7th location,…Without the number of columns the compiler is not able to organize memory for the array.

=>Initializers

The initializers of an array can work in two ways:
initializers for each row are enclosed in second class of { } ;
all initializers are enclosed in only one { } , and apply to elements first by row then by column.

4.8 String Handling Functions

Their function prototypes are in “string.h” header file. Data type size_t used in these functions is an unsigned integer type.

char * strcpy(char * s1, const char * s2)                //copy s2 into s1
char * strncpy(char * s1, const char * s2, size_t n)     //copy n of s2 into s1
char * strcat(char * s1, const char * s2)                //append s2 to s1
char * strncat(char * s1, const char * s2, size_t n)     //append n of s2 to s1
int strcmp(const char * s1, const char * s2)             //compare s1 with s2. Return positive, 0 or negative
int strncmp(const char * s1, const char * s2, size_t n)  //compare n of s1 with s2
char * strtok(char * s1, const char * s2)                //break s1 into tokens separated by s2
size_t strlen(const char * s)                            //length of s, not counting NULL

Popularity: 22%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image