Initialization a pointer to an array of pointers

May 6, 2014 at 11:12am
Hi averyone!
Here is a pointer to array of four pointers and we can easily initialize it in this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  char *ch[4];
	for(int i=0; i<4; i++)
	{
		*(ch+i)=new char;
		**(ch+i)=(char)(i+65);
		std::cout<<"**(ch+"<<i<<")= "<<**(ch+i)<<'\n';
	}
	
	char *(*PtrToArrayOfPtr_s)[4]=0;
	PtrToArrayOfPtr_s=&ch;

	for(int i=0; i<4; i++)
	{

		std::cout<<"**(*PtrToArrayOfPtr_s+"<<i<<")= "<<**(*PtrToArrayOfPtr_s+i)<<'\n';
	}

The output will be:
**(ch+0)=A
**(ch+1)=B
**(ch+2)=C
**(ch+3)=D
**(*PtrToArrayOfPtr_s+0)=A
**(*PtrToArrayOfPtr_s+1)=B
**(*PtrToArrayOfPtr_s+2)=C
**(*PtrToArrayOfPtr_s+3)=D
So all these things are simple and clear enough there fore.

The problems starts when I am trying to initialize PtrToArrayOfPtr_s by the operator "new" to allocate mamory in dinamic part of mamory.

Here are some of my tries:
1
2
PtrToArrayOfPtr_s=new char*(*)[4];
PtrToArrayOfPtr_s=new char**[4];


All of them are not working of course.

Please HELP!
May 6, 2014 at 12:42pm
Why do you want to do such a thing?
May 6, 2014 at 1:05pm
The compiler needs to know how many char arr[4]s that you want:
1
2
char *(*arr)[4] = nullptr;
arr = new char *[99][4];


The hardcoded 4 makes it a little obscure:
1
2
3
char ***arr;
arr = new char **;
*arr = new char *[4];
May 6, 2014 at 2:10pm
Thanks a lot, Lowest0ne!!! It is really so!!!!
keskiverto, when you declare variables in function's body, they are in stack and when you allocate memory to pointer with operator "new" this memory is in dinamic memory wich is much bigger then stack. So it is on your decision what memory you want to use......:-)
May 6, 2014 at 8:11pm
Ok, where are the characters of this then:
std::string ch {"ABCD"};

That was not my question though. Why to use such tricky types as in char *(*foo)[4] ?
May 6, 2014 at 10:30pm
keskiverto, you should read some books about organisation memory in c++ programs. There are 3 types of memory: static, dynamic, stack. "ABCD" will be in static memory. About the question "Why to use such tricky types as in char *(*foo)[4]"-this is a forum of the beginners and if i write question here, then I am a beginner in c++ and I am learning now. And some learning exerсises are made for better understanding the ideology of pointers and are far from the real (at work) tasks.
Topic archived. No new replies allowed.