Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

howto pointer to an array of char [roll2] 1

Status
Not open for further replies.

AMosmann

Programmer
May 27, 2003
82
DE
please tell me:

How can I define a pointer to an array of MyType,
how to define an array of Pointer to MyType,
how to define a pointer to an array of pointer to MyType
and how to allocate memory for all this?

//pointer to array of MyType
MyType *(MyVars[])
MyVar = ((MyType *)[]) new MyType[10];

//array of pointer to MyType
MyVar (*MyType)[10];

//pointer to an array of pointer to MyType
MyType *((*MyType)[]);
MyVar= (((MyType*)[])*) new (MyType*)[10];

Is anything of this correct? What is wrong?

Greetings Andreas
 
Maybe this will help?
Code:
typedef struct{
	int num;
}mytype;

void doArray(){
	// declare a static array
	mytype types[] = {{10},{12}};
	// use it as a pointer
	mytype* p = types;
	cout << &quot;zero: &quot; << p->num << endl;
	p++;
	cout << &quot;one: &quot; << p->num << endl;

	// stack based array of pointers to mytype instances
	mytype* ptypes[10];	// there are 10 invalid pointers of type &quot;mytype&quot;
	for(int n=0; n<10; n++){
		// allocate each pointer
		ptypes[n] = new mytype;		// new structure allocated to unknown &quot;num&quot; value
		// give it a value we can check
		ptypes[n]->num = n + 10;
	}

	for(n=0; n<10; n++)
		cout << n << &quot;: &quot; << ptypes[n]->num << endl;

	// heap based array of pointers
	mytype** pheap = new mytype* [5];
	for(n=0; n<5; n++){
		// allocate each pointer
		pheap[n] = new mytype;
		// set some value we can check
		pheap[n]->num = n + 20;
	}

	for(n=0; n<5; n++)
		cout << n << &quot;: &quot; << pheap[n]->num << endl;
	// exit with memory leaks
}

-pete
 
not completely, the most interesting part for me is, how to allocate an array of MyType on the heap, because all tries like

MyType *MyVar[];
MyVar = ANY_TEXT new ANY_SIGN MyType[10];

with all brackets I know did not work ...

Cant be that difficult, is it?

[bomb]

Greetings Andreas
 
Code:
void heapArray(){
	// 10 instances allocated but not initialized
	mytype* myarray = new mytype[10];
	for(int n=0; n<10; n++){
		// initialize
		myarray[n].num = 20;
		// use
		cout << &quot;n: &quot; << n + myarray[n].num << endl;
	}

	//exit with memory leak
}

-pete
 
Compiles, thx,

to free this memory I use

delete [] MyVar;

?

[spin][rofl][spin]

Greetings Andreas
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top