Showing posts with label arrays. Show all posts
Showing posts with label arrays. Show all posts

Wednesday, September 1, 2010

2-D Array Memory Layout

Two kinds of multi-dimensional arrays.

There are two basic ways of implementing 2-dimensional arrays: rectangular, sequential, two-dimensional arrays and arrays of arrays. Some languages use one method, some another, and some both. C++ allows both methods, and each has its advantages and disadvantages.
  • rectangular sequential arrays. In this case the rows are laid out sequentially in memory. This provides simplicity in memory management and a slight speed advantage. This is the kind of array C/C++ creates by default.
  • Arrays of arrays. In this style each element of a one-dimensional array is a pointer to another array. This is a common way to create an array of C-strings (a zero-terminated array of characters). This is also useful if the rows are uneven length or are dynamically allocated. The disadvantage is that memory management is more complex, often requiring dynamic allocation and deallocation. This is the only kind of multi-dimensional array in Java. See Arrays of Arrays.

Rectangular arrays allocated in memory by row

Let's see how the memory is allocated for this array.
char ttt[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', ' '}
};
The memory for this array could be visualized as in the diagram to the right, which identifies a few cells by their subscripts.
2D array memory representation
2D array memory representation
Because memory is addressed linearly, a better representation is like the diagram to the left.

Computing the address of an array element

C++ must compute the memory address of each array element that it accesses. C++ does this automatically, but it helps to understand what's going on "under the hood". Assume the following declaration:
char a[ROWS][COLS];  // assume ROWS and COLS are const ints
Because arrays are laid out in memory by row, each row length is COLS (the number of columns is the size of a row). Let's assume that you want to find the address of a[r][c]. The baseAddress of the array is the address of the first element. The rowSize is COLS in the above example. The elementSize is the number of bytes required to represent the data (typically 1 for char, 4 for int, 4 for float, and 8 for double.
address = baseAddress + elementSize * (r*rowSize + c);
Note
  • The number of rows (ROWS) is not used in the computation.
  • Because the number of rows is not used, there is no need to pass it when declaring a formal array parameter for a two-dimension array.

Arrays of Arrays

Array of C-strings

An array of C-strings is an array of arrays. Here is an example.
char* days[] = {"Mon", "Tue", "Wed", "Thu", "Fri"};
In the above days array each element is a pointer to a string, and they don't have to be the same size. For example,
char * greetings[] = {"Hello", "Goodbye", "See you later"};

Parameters to main

When the main function is called, it is passed the name of the program that is being run and all the tokens (words) on the remainder of the line that was used to run the program. These are passed to the main as an array of C-strings and the number of elements in the array. Here is a main program that prints these parameters.
#include 
using namespace std;

int main(int argc, char* argv[]) {
for (int i=0; i
cout << argv[i] << endl;
}
return 0;
}

Array of pointers or pointer to pointer

Because arrays and pointers are so interchangeable, you can write the header of main like this also:
int main(int argc, char* argv[]) { ...

2-Dimensional Arrays

Data that is in rows and columns is usually stored in 2-dimensional arrays.

Declaring of 2-dimensional arrays

Two-dimensional arrays are declared by specifying the number of rows then the number of columns.
int  a[30][10];  // declares an int array of 30 rows and 10 columns.
char ticTacToeBoard[3][3]; // three rows and three columns of chars.

Initializing 2-dimensional arrays

Unless specified, all initial values of arrays are garbage. You can specify initial values by enclosing each row in curly braces like this:
char ticTacToeBoard[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', ' '}
};
If some elements are omitted in the initialization list, they are set to zero.

Subscripting 2-dimensional arrays

Write subscripts as x[row][col]. Passing over all elements of a two-dimensional array is usually done with two nested for loops.
// clear the board
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
ticTacToeBoard[row][col] = ' ';
}
}

Passing 2-dimensional arrays as parameters

C++ doesn't care about bounds, but it needs to compute the memory address given the subscripts (see below). To do this it needs to know the row width (number of columns). Therefore formal 2-dimensional array parameters must be declared with the row size, altho the number of rows may be omitted. For example,
void clearBoard(ticTacToeBoard[][3]) {
. . .
}

Dynamic allocation of arrays in cpp

The problems with fixed size arrays

Declaring an array with a fixed size like
int a[100000];
has two typical problems:
  • Exceeding maximum. Choosing a real maximum is often impossible because the programmer has no control over the size of the data sets the user is interested in. Erroneous assumptions that a maximum will never be exceeded are the source of many programming bugs. Declaring very large arrays can be extremely wasteful of memory, and if there are many such arrays, may prevent the program from running in some systems.
  • No expansion. Using a small size may be more efficient for the typical data set, but prevents the program from running with larger data sets. If array limits are not checked, large data sets will run over the end of an array with disastrous consequences. Fixed size arrays can not expand as needed.
These problems can be avoided by dynamically allocating an array of the right size, or reallocating an array when it needs to expand. Both of these are done by declaring an array as a pointer and using the new operator to allocate memory, and delete to free memory that is no longer needed.
This is exactly what is vector does, but let's see how it's done with an array.

Declare array as a pointer, allocate with new

To create a variable that will point to a dynamically allocated array, declare it as a pointer to the element type. For example,
int* a = NULL;  // pointer to an int, intiallly to nothing.
A dynamically allocated array is declared as a pointer, and must not use the fixed array size declaration. The above declaration creates a pointer, but doesn't yet allocate any memory to it.

Allocate an array with code>new

When the desired size of an array is known, allocate memory for it with the new operator and save the address of that memory in the pointer. Remember: Pointers may be subscripted just as arrays are. The example below reads in a number and allocates that size array.
int* a = NULL;   // Pointer to int, initialize to nothing.
int n; // Size needed for array
cin >> n; // Read in the size
a = new int[n]; // Allocate n ints and save ptr in a.
for (int i=0; i
a[i] = 0; // Initialize all elements to zero.
}
. . . // Use a as a normal array
delete [] a; // When done, free memory pointed to by a.
a = NULL; // Clear a to prevent using invalid memory reference.

Freeing memory with delete

When you are finished with dynamically allocated memory, free it with the delete operator. After memory is freed, it can be reused by later new requests. Memory that your program didn't free will be freed when the program terminates. Never free memory that wasn't dynamically allocated - the results are unpredictable.
delete [] a;  // Free memory allocated for the a array.
a = NULL; // Be sure the deallocated memory isn't used.

Use [] when deleting arrays

You must specify "[]" when deleting an array, but not for a single value. It isn't possible to delete only part of an array.

Do you have to reset a pointer after delete?

Following the delete in these examples, I reset the pointer to NULL. This isn't strictly necessary, but it's very good practice so that any use of the pointer will produce an error. Attempts to use memory location 0, which is the normal default value of NULL, will be blocked by the way most operating systems allocate memory.
Why doesn't delete reset the pointer? It does in some systems, but the language specification does not require it, so not all systems do it.

2d array and pointers in details

Expand|Select|Wrap|Line Numbers
  1. int array[5][10];
  2.  
Here array is the address of array[0]. Since array[0] is an array of 10 int, array is the address of an array of 10 int. You can assign the name array to a pointer to an array of 10 int:
Expand|Select|Wrap|Line Numbers
  1. int array[5][10];
  2.  
  3. int (*ptr)[10] = array;
  4.  
Fourth, when the number of elements is not known at compile time, you create the array dynamically:

Expand|Select|Wrap|Line Numbers
  1. int* array = new int[value];
  2. int (*ptr)[10] = new int[value][10];
  3. int (*ptr)[10][15] = new int[value][10][15];
  4.  
In each case value is the number of elements. Any other brackets only describe the elements.

Using an int** for an array of arrays is incorrect and produces wrong answers using pointer arithmetic. The compiler knows this so it won't compile this code:

Expand|Select|Wrap|Line Numbers
  1. int** ptr = new int[value][10];    //ERROR
  2.  
new returns the address of an array of 10 int and that isn't the same as an int**.

Likewise:
Expand|Select|Wrap|Line Numbers
  1. int*** ptr = new int[value][10][15];    //ERROR
  2.  
new returns the address of an array of 10 elements where each element is an array of 15 int and that isn't the same as an int***.

Returning Multi-dimensional Arrays from Functions

Returning an array from a function only has meaning if the array was created by the function. Otherwise,
no return is necessary since an existing array is passed by the address. However, if the function has
created the array on the heap, you can return the address of element 0.

The problem here is that you can't use the function return type unless you a) return a type or
b) return a pointer to a type. That is, you cannot return a pointer to an array since an array is not
a type. So, if you create an array of int you can return the array as an int*:

Expand|Select|Wrap|Line Numbers
  1. int* func(int arg)
  2. {
  3.     int* temp = new int[arg];
  4.     return temp;
  5. }
  6. int main()
  7. {
  8.     int* arr = func(5);
  9. }
  10.  
This does not work when you create a multi-dimensional array:
Expand|Select|Wrap|Line Numbers
  1. int (*)[5] func(int arg)   // ERROR: Cannot return an array
  2. {
  3.     int (* temp)[5] = new int[arg][5];
  4.     return temp;
  5. }
  6. int main()
  7. {
  8.     int (* arr)[5] = func(4);
  9. }
  10.  
In this case you could pass in the address of a pointer to an array of 5 int:
Expand|Select|Wrap|Line Numbers
  1. void func(int arg, int (**rval)[5])
  2. {
  3.     int (* temp)[5] = new int[arg][5];
  4.     *rval = temp;
  5. }    
  6. int main()
  7. {
  8.     int (* arr)[5] = 0;
  9.     func(4, &arr);
  10.     //arr is now a [4][5] array of int
  11. }
  12.  
However, if you need to use the function as an RVAL, then you need to return a type. Here the easiest thing to do is define a type to be a pointer to an element of your multi-dimensional array. In this example you would need a pointer to an array of 5 int:

Expand|Select|Wrap|Line Numbers
  1. typedef int (*IntArray5Ptr)[5]; 
Now you have a type that can be returned:

Expand|Select|Wrap|Line Numbers
  1. IntArray5Ptr func(int arg)    
  2. { 
  3.     int (* temp)[5] = new int[arg][5]; 
  4.     return temp; 
  5. }
  6.  
  7. int main() 
  8. { 
  9.     int (* arrA)[5] = func(4); 
  10. } 
You can return a pointer to type in addition to returning a type. So you could define a type to be an element of your array (in the example this is an array of 5 int) and return a pointer to that type:

Expand|Select|Wrap|Line Numbers
  1. typedef int IntArray5[5]; 
  2.  
  3. IntArray5* funcB(int arg) 
  4. { 
  5.     int (* temp)[5] = new int[arg][5]; 
  6.     return temp; 
  7. } 
  8.  
  9.  
  10. int main() 
  11. { 
  12.     int (* arr)[5] = func(4); 
  13. } 
Finally, as was stated at the beginning of this article: There are no multi-dimensional arrays in C++.
Therefore, a function could just create a one-dimensional array of the correct number of elements and return
the address of element 0. In this case, element 0 is a type and you can use the return type of a function
to return a pointer to a type. Then the calling function could typecast the return so the array can be
used with muliple dimensions:

Expand|Select|Wrap|Line Numbers
  1. int* func(int arg)
  2. {
  3.     int * temp = new int[arg];
  4.     return temp;
  5. }    
  6. int main()
  7. {
  8.     //This is arr[60]
  9.     int* arr = func(60);
  10.  
  11.     //This is arr[12][5] --> 12 x 5 = 60
  12.     int (*arr1)[5] = (int(*)[5])func(60);
  13.  
  14.     //This is arr[3][4][5] -> 3 * 4 * 5 = 60
  15.     int (*arr2)[4][5] = (int(*)[4][5])func(60);
  16.  
  17.     //This is arr[1][3][4][5] -> 1*3*4*5 = 60;
  18.     int (*arr3)[3][4][5] = (int(*)[3][4][5])func(60);
  19.  
  20.  
  21.  
  22. }
  23.  

Tuesday, August 31, 2010

Arrays revealed (1 d mainly) in cpp

First, there are only one-dimensional arrays in C or C++. The number of elements is put between brackets:

Expand|Select|Wrap|Line Numbers
  1. int array[5];
  2.  
That is an array of 5 elements each of which is an int.

Expand|Select|Wrap|Line Numbers
  1. int array[];
  2.  
won't compile. You need to declare the number of elements.

How to bound check arrays in cpp / c

Bound checking in cpp /c is headache....
char *strcpy(char *dest, const char *src)
{
char *save = dest;
while(*dest++ = *src++);
return save;
}

//main func
char *src = "hello to c programming language";
char dest[12];

strcpy(dest,src); //calling function

Here we have no bound check on dest size or src size. When we pass it to function it is perfectly alright but
problem is dest is array which is just 12 bytes long...but src is larger string...

So if programmer is lucky , he gets Error - "Segmentation fault"
else in worse case, he gets his core dumped...that is his memory may have changed the effect of it can be seen after few days.

What's the solution?
We cant change this library function to check bound check, like sending size to it with both src and dest...because many programs might be using it...and this change may hamper these million of programs. So it is the responsibility of programmer to check whether he has provided enough space or not?
Note: There is no way right now to check bounds by [] operator.

Vectors
A vector will do bounds checking if you use the at() function, for example:
std::vector v(5);
v
.at(3) = 10;
v
.at(5) = 20; // throws an exception, std::out_of_range
However, if you use operator[], there is no bounds checking. (And accessing non-existent elements leads to undefined behavior.)

Thursday, August 5, 2010

C arrays

Arrays are useful critters because they can be used in many ways. For example, a tic-tac-toe board can be held in an array. Arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.

Think about arrays like this:
[][][][][][] 
Each of the bracket pairs is a slot(element) in the array, and you can put information into each one of them. It is almost like having a group of variables side by side.

This would make an integer array with 100 slots, or places to store values(also called elements). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. 0-99 in a 100 element array, for example.

What can you do with this simple knowledge? Lets say you want to store a string, because C had no built-in datatype for strings, it was common to use arrays of characters to simulate strings. (C++ now has a string type as part of the standard library.)

For example:
char astring[100]; 
will allow you to declare a char array of 100 elements, or slots. Then you can receive input into it it from the user, and if the user types in a long string, it will go in the array. The neat thing is that it is very easy to work with strings in this way, and there is even a header file called cstring. There is another lesson on the uses of strings, so its not necessary to discuss here.

The most useful aspect of arrays is multidimensional arrays. How I think about multi-dimensional arrays:
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]
This is a graphic of what a two-dimensional array looks like when I visualize it.

For example:
int twodimensionalarray[8][8];
declares an array that has two dimensions. Think of it as a chessboard. You can easily use this to store information about some kind of game or to write something like tic-tac-toe. To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can even make a three dimensional array, though you probably won't need to. In fact, you could make a four-hundred dimensional array. It would be confusing to visualize, however. Arrays are treated like any other variable in most ways. You can modify one value in it by putting:
arrayname[arrayindexnumber] = whatever; 
or, for two dimensional arrays
arrayname[arrayindexnumber1][arrayindexnumber2] = whatever;
However, you should never attempt to write data past the last element of the array, such as when you have a 10 element array, and you try to write to the [10] element. The memory for the array that was allocated for it will only be ten locations in memory, but the next location could be anything, which could crash your computer.

You will find lots of useful things to do with arrays, from storing information about certain things under one name, to making games like tic-tac-toe. One suggestion I have is to use for loops when access arrays.
#include 

using namespace std;

int main()
{
int x;
int y;
int array[8][8]; // Declares an array like a chessboard

for ( x = 0; x < 8; x++ ) {
for ( y = 0; y < 8; y++ )
array[x][y] = x * y; // Set each element to a value
}
cout<<"Array Indices:\n";
for ( x = 0; x < 8;x++ ) {
for ( y = 0; y < 8; y++ )
cout<<"["<<<"]["<<<"]="<< array[x][y] <<" ";
cout<<"\n";
}
cin.get();
}
Here you see that the loops work well because they increment the variable for you, and you only need to increment by one. Its the easiest loop to read, and you access the entire array.

One thing that arrays don't require that other variables do, is a reference operator when you want to have a pointer to the string. For example:
char *ptr;
char str[40];
ptr = str; // Gives the memory address without a reference operator(&)
As opposed to
int *ptr;
int num;
ptr = &num; // Requires & to give the memory address to the ptr
The reason for this is that when an array name is used as an expression, it refers to a pointer to the first element, not the entire array. This rule causes a great deal of confusion, for more information please see our Frequently Asked Questions.

Tuesday, August 3, 2010

Some udfs for arrays in cpp

void printArray (int *array,int size)
{
int i;
for (i = 0; i <= size; i++)
cout << array[i] << " ";
cout << endl;
}

Wednesday, July 28, 2010

Some udfs for arrays in c

1D arrays
Printing 1 D arrays
void printArray (int *array,int size)
{
int i;
for (i = 0; i < size; i++)
     printf("%d",array[i]);
printf("\n");
}
2 D arrays 
Printing 2D arrays
void printArray(int **array, int m, int n)
{
           for(i = 0; i < nrows; i++)  
              for(j= 0; j < nrows; i++)  
                         printf("%d",array[i][j]);
}

Allocating and Deallocating 2 D Arrays 

/*   allocate2D
/*   function to dynamically allocate 2-dimensional array using malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows and
/*   columns.
*/
void allocate2D(int** array, int nrows, int ncols) {
     
     /*  allocate array of pointers  */
     array = ( int** )malloc( nrows*sizeof( int* ) );
     
     /*  allocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          array[i] = ( int* )malloc( ncols*sizeof( int ) );
     }
}
/*   deallocate2D
/*   corresponding function to dynamically deallocate 2-dimensional array using
/*   malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows. 
/*   as with all dynamic memory allocation, failure to free malloc'ed memory
/*   will result in memory leaks
*/
void deallocate2D(int** array, int nrows) {
     
     /*  deallocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          free(array[i]);
     }
     
     /*  deallocate array of pointers  */
     free(array);
     
}
/*   EXAMPLE USAGE:   
int** array1;

allocate2D(array1,1000,1000); //allocates a 1000x1000 array of ints

deallocate2D(array1,1000);    //deallocates the same array

*/

Saturday, December 5, 2009

C code to return a string from a function

This C program wont work!


char *myfunction(int n)
{
   char buffer[20];
   sprintf(buffer, "%d", n);
   return retbuf;
}



This wont work either!


char *myfunc1()
{
  char temp[] = "string";
  return temp;
}


char *myfunc2()
{
   char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
   return temp;
}


This will work
The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in by the caller function, or to memory obtained using malloc(), but not to a local array. 


char *myfunc()
{
   char *temp = "string";
   return temp;
}

int main()
{
   puts(myfunc());
}



So will this


calling_function()
{
  char *string;
  return_string(&string);
  printf(?\n[%s]\n?, string);
}

boolean return_string(char **mode_string /*Pointer to a pointer! */)
{
   *string = (char *) malloc(100 * sizeof(char));
   DISCARD strcpy((char *)*string, (char *)?Something?);
}

Finding whether 2 arrays are intersecting


Here are 2 arrays:
A1   1 8 7 5 6
A2   0 9 6 4 2

These two are intersecting at 6.
Complexity? 



Solution:
This can be solved using Hash Tables.
Take 1 Hash Table.
Insert elements from A1 in Hast Table as key and put value in front of them
(In case elemente get repeated increment the value count).
Now traverse the second array A2 and check for element as a key.If you find
it decrement the value and put it in array else continue to next element in
A2.

C code to dynamically allocate one, two and three dimensional arrays (using malloc())

One Dimensional Array
int *myarray = malloc(no_of_elements * sizeof(int));

//Access elements as myarray[i]

2 Dimensional Array
Method1
int **myarray = (int **)malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
 myarray[i] = malloc(ncolumns * sizeof(int));
//allocating 1 D array = number of elements in column
}

// Access elements as myarray[i][j]

Method 2 (Contagious Allocation)
int **myarray = (int **)malloc(nrows * sizeof(int *));
myarray[0] = malloc(nrows * ncolumns * sizeof(int));

for(i = 1; i < no_of_rows; i++)
  myarray[i] = myarray[0] + (i * ncolumns);

// Access elements as myarray[i][j]

In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. 

Method 3
int *myarray = malloc(nrows * ncolumns * sizeof(int));

// Access elements using myarray[i * ncolumns + j].
i.e. you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j].  (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) 

Method4
Finally, you can use pointers-to-arrays:
 int (*array4)[NCOLUMNS] =
(int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
, but the syntax gets horrific and all but one dimension must be known at compile time.
Three Dimensional Array

#define MAXX 3
#define MAXY 4
#define MAXZ 5

main()
{
    int ***p,i,j;
    
p=(int ***) malloc(MAXX * sizeof(int ***));

    for(i=0;i
    {
        p[i]=(int **)malloc(MAXY * sizeof(int *));
        for(j=0;j
            p[i][j]=(int *)malloc(MAXZ * sizeof(int));
//allocating 1D array of size = size of last dimensional...So we have to allocate
//n1*n2 such arrays...where n1 and n2 are 2 such dimensional.
    }
     
    for(k=0;k
        for(i=0;i
            for(j=0;j
                p[i][j][k]=;

}

Saturday, June 27, 2009

Passing 2 D array to function

double f(double values[][4], int n);

int main() {
  double beans[3][4] = {
                         { 1.0,  2.0,  3.0,  4.0},
                         { 5.0,  6.0,  7.0,  8.0},
                         { 9.0, 10.0, 11.0, 12.0}
                       };

 printf(" %f\n",f(beans, sizeof beans/sizeof beans[0]));
 getch();
  return 0;
}

double f(double array[][4], int size) {
  double sum = 0.0;
  int i,j;
  for( i = 0 ; i < size ; i++)      
    for( j = 0 ; j < 4 ; j++)       
      sum += array[i][j];
     
  return sum;
}

Another method is you dynamically allocate array and than pass its pointer to the function.
#include
#include
#include
// Ref : http://www.eskimo.com/~scs/cclass/int/sx9b.html
void printArray(int **array, int m, int n)
{
     int i,j;
 for(i=0;i
   for( j=0;j
printf("%d\n",array[i][j]);

     printf("\n");
}
int main()
{
      int i,j,k=0, m=5, n=20;
      int **a=(int **)malloc(m*sizeof(int *));
      for(i=0;i
      for(i=0;i      //for(i=0;i
      printArray(a,m,n);
      system("PAUSE");
      return 0;
}