Question

The CreateFileMapping function returns a pointer to a memory mapped file, and I want to treat that memory mapping as an array.

Here's what I basically want to do:

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

Except apparently I can't simply wave my arms and declare that a pointer is now an array.

Do you guys have any idea how I can do this? I don't want to copy the the values the pointer is pointing to into the array because that will use too much memory with large files.

Thanks a bunch,

Was it helpful?

Solution

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

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

OTHER TIPS

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

But in your case, for your purposes they are.

You have a pointer.

You can give it a subscript.

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

pointer[0] is the first character 'h'

pointer[1] is the second character 'e'

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

"In C/C++, pointers and arrays are not the same thing." is true, but, the variable name for the array is the same as a pointer const (this is from my old Coriolis C++ Black 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.

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

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

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

You can use a C-style cast:

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

Or the preferred reinterpret cast:

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

I was also searching for this answer. What you need to do is to create your own type of array.

    static const int TickerSize = 1000000;
    int TickerCount;
    typedef char TickerVectorDef[TickerSize];

You can also cast your pointer into this new type. Otherwise you get "Compiler error C2440". It has to be a fixed size array though. If you only use it as a pointer, no actual memory is allocated (except 4-8 bytes for the pointer itself).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top