views:

1149

answers:

5

Hi,

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,

+15  A: 

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

char* p = (char*)CreateFileMapping(...);
p[123] = 'x';
...
Pavel Minaev
Awesome, thanks!
Zain
+1  A: 

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.

Michael Krelin - hacker
+5  A: 

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.

Will
To the language, pointers and arrays are the same thing. An array is a pointer to the first object in a series.
@dnh828, you're wrong. Try using `sizeof` on an array and a pointer of the "same" type. Or assign one array to another. A pointer to array is also distinct from pointer to pointer. And so on.
Pavel Minaev
To be more specific, in C/C++, arrays _decay_ to pointers _in certain contexts_. Not always.
Pavel Minaev
a point and an array are most definitely not the same thing in C/C++. Just because an array is able to decay into a pointer doesn't make them the same.
jalf
And the reason that an array is different is *exactly* that the compiler knows how big it is (or at least how big it is in D-1 dimensions).
dmckee
Interestingly, p[3] == 3[p] == *(p+3).
Jurily
A: 

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';
teambob
A: 

"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.

cvsdave