HTML

html content help to improve the coding

Wednesday, 28 March 2012

PROGRAM FOR ARRAY IN C++



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream.h>

void main() {
 const int rows = 4;
 const int cols = 4;

 // declaration
 int ** a;

 // allocation
 a = new int*[rows];
 for(int i = 0; i < rows; i++)
  a[i] = new int[cols];

 // initialization
 for(int j = 0; j < rows; j++)
  for(int i = 0; i < rows; i++)
   a[i][j] = 0;
}

I just give you a simple example here:

1
2
3
4
5
6
void main() {
 byte * str;
 str = (byte *) calloc(100, sizeof(byte)); // this is specific for arrays
 // or: str = (byte *) malloc(100);  // this is only for byte arrays
 free(str);
}


I hope it can help you!
Good luck!you can use the new instruction only to allocate object of a class type,
you defined byte as a unsigned char, this is a primitive type, it's not a class so it doesn't work.

you may use the C calloc(...) function but it's not very simple at first sight

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream.h>

typedef unsigned char byte;

byte ** createByteMatrix(unsigned int rows, unsigned int cols) {
 byte ** matrix;
 matrix = (byte **) calloc(cols, sizeof(byte *));
 for(unsigned int i = 0; i < cols; i++)
  matrix[i] = (byte *) calloc(rows, sizeof(byte));
 return matrix;
}

void main() {
 byte ** BitmapArray;
 BitmapArray = createByteMatrix(5, 5);
 BitmapArray[0][0] = 0;
}
Any way to make a multi dimensional dynamic array?

1
2
3
4
5
6
typedef unsigned char byte;
byte * BitmapArray;

void whatever() {
     BitmapArray = new byte[5][5];
}

No comments:

Post a Comment