Convert a pointer to an array in C++

▼魔方 西西 提交于 2019-12-22 17:36:10

问题


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,


回答1:


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

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



回答2:


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.




回答3:


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




回答4:


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.




回答5:


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



回答6:


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



来源:https://stackoverflow.com/questions/1309129/convert-a-pointer-to-an-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!