Sun Feb 7 14:06:14 CET 2010

cpp.png Pointer and Arrays

Hello. I would like to say 'hello again'. :-)

As some of you noticed, there is a little problem while creating an array and a pointer of it in C++. For doing that, you are supposed to write something like:

int data[50];		// declare an (static) array
int *p_data = data;	// make a pointer of it

// declare a function, which gets the pointer of the data array
void function(..., int* p_data, ...);

// Call-by-reference
function(..., p_data, ...)

If you don't want to have a static array but a dynamic one, you need to ask the user for the length and then reserve some memory for it.
Thanks to: Fred Swartz:

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<n; 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.

If you need it all over dynamic, to grow and shrink depending on what the user wants, you could use malloc and remalloc memory for an array (like you would do it in C). But you could also use std::vector (declared in vector.h) which does all what you need:

std::vector<int>  data;
std::vector<int>* p_data = &data;

// declare a function, which gets the pointer of the data vector
void function(..., int* p_data, ...);

// Call-by-reference
function(..., p_data, ...)

Posted by Sebastian Wieseler | Permalink | Categories: projects/programming |