[ACCEPTED]-Convert a pointer to an array in C++-memory-mapping

Accepted answer
Score: 22

You do not need to. You can index a pointer 1 as if it was an array:

char* p = (char*)CreateFileMapping(...);
p[123] = 'x';
...
Score: 5

In C/C++, pointers and arrays are not the 7 same thing.

But in your case, for your purposes 6 they are.

You have a pointer.

You can give 5 it a subscript.

E.g. a char* pointer points 4 to the start of "hello"

pointer[0] is the 3 first character 'h'

pointer[1] is the second 2 character 'e'

So just treat it as you are 1 thinking about an array.

Score: 2

"In C/C++, pointers and arrays are not the 4 same thing." is true, but, the variable 3 name for the array is the same as a pointer 2 const (this is from my old Coriolis C++ Black 1 Book as I recall). To wit:

char carray[5];
char caarray2[5];
char* const cpc = carray;    //can change contents pointed to, but not where it points

/*
  cpc = carray2;    //NO!! compile error
  carray = carray2; //NO!! compile error - same issue, different error message
*/

cpc[3] = 'a';  //OK of course, why not.

Hope this helps.

Score: 1

But how's pointer different from array? What's 2 wrong with

char *Array = (char*)CreateFileMapping(...);

You can treat the Array more or less 1 like you would treat an array from now on.

Score: 1

You can use a C-style cast:

char *p = (char*)CreateFileMapping(...);
p[123] = 'x';

Or the preferred 1 reinterpret cast:

char *p std::reinterpret_cast<char*>(CreateFileMapping(...));
p[123] = 'x';

More Related questions