Array and pointer
can someone explain what is happening in the memory when i declare this.
i saw this kind of code few times ago but i don't remember how to use it.
It is declaring an unsized array of pointers to chars.
The way is it declared is only useful when using with a parameter to a method/function
void SomeFunc( char *name[] param1 );
Below are some pointer examples that you would use in code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// pointer to array of 4 char's, max string it can hold is 3 + NULL terminator
char *pPtrToChars = new char [4];
strcpy( pPtrToChars, "ABC" );
// array of pointers to array's of char's
// size is fixed at 2 during compile time
char *ArrayOfCharPtrs[2];
ArrayOfCharPtrs[0] = new char [4];
ArrayOfCharPtrs[1] = new char [4];
strcpy( ArrayOfCharPtrs[0], "DEF" );
strcpy( ArrayOfCharPtrs[1], "GHI" );
// pointer to array of pointers to array's of char's
// size is dynamic, set at runtime
int numArrays = 2;
char **pPtrToArrayOfCharPtrs = new char * [numArrays];
pPtrToArrayOfCharPtrs[0] = new char [4];
pPtrToArrayOfCharPtrs[1] = new char [4];
strcpy( pPtrToArrayOfCharPtrs[0], "JKL" );
strcpy( pPtrToArrayOfCharPtrs[1], "MNO" );
cout << pPtrToChars << endl;
cout << ArrayOfCharPtrs[0] << endl;
cout << ArrayOfCharPtrs[1] << endl;
cout << pPtrToArrayOfCharPtrs[0] << endl;
cout << pPtrToArrayOfCharPtrs[1] << endl;
|
i am a super noob so please bare with me.
i didn't understood the line
|
char *pPtrToChars = new char [4]; // 0_o brain damage
|
can you please explain it in very simple language.
i never used "new" keyword.
i can understand the rest of the code easily(because thats basic stuff :P).
new is c++ equivalent of malloc. Used to create dynamic memory. This line is creating an array of 4 chars.
static version would be
char ArrayOf4Chars[4];
Thanks for help.
Topic archived. No new replies allowed.