Convert pointer to array in C ++
The CreateFileMapping function returns a pointer to a memory mapped file and I want to treat this memory mapping as an array.
Here's what I basically want to do:
char Array[] = (char*) CreateFileMapping(...);
Except, apparently, I can't just wave my arms around and declare that the pointer is now an array.
Do you guys know how I can do this? I don't want to copy the values pointed to by the pointer into the array because they will use too much memory with large files.
Thanks a bunch,
You do not need. You can index the pointer as if it were an array:
char* p = (char*)CreateFileMapping(...);
p[123] = 'x';
...
In C / C ++, pointers and arrays are not the same thing.
But in your case, it is for your purposes.
You have a pointer.
You can give it an index.
eg. a char * indicates the start of "hello"
pointer [0] is the first character 'h'
pointer [1] - second character 'e'
So just treat it the way you think of an array.
"In C / C ++, pointers and arrays are not the same thing." true, but the variable name for the array is the same as a const pointer (this is, as I recall, from my old Coriolis C ++ Black Book). 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 it helps.
But how does a pointer differ from an array? What is wrong with
char *Array = (char*)CreateFileMapping(...);
You can relate to Array
more or less, since now you will be processing the array.
You can use C style:
char *p = (char*)CreateFileMapping(...);
p[123] = 'x';
Or the preferred reinterpretation:
char *p std::reinterpret_cast<char*>(CreateFileMapping(...));
p[123] = 'x';
I was looking for this answer as well. What you need to do is create your own array.
static const int TickerSize = 1000000;
int TickerCount;
typedef char TickerVectorDef[TickerSize];
You can also cast your pointer to this new type. Otherwise, you will receive "Compiler error C2440". However, it must be a fixed size array. If you only use it as a pointer, no actual memory is allocated (except 4-8 bytes for the pointer itself).