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,

+2


source to share


6 answers


You do not need. You can index the pointer as if it were an array:



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

      

+22


source


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.

+5


source


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

+2


source


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.

+1


source


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';

      

+1


source


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

-1


source







All Articles