Convert a pointer to an array in C++

倖福魔咒の 提交于 2019-12-06 11:01:46

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

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

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.

cvsdave

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

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