Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ - Casting pointer to Array (int* to int[2])

How do I cast or convert an int* into an int[x]?

First, I know that pointers can be indexed. So I know that I can loop through the pointer and array and manually convert the pointer. (eg. a for loop with arr[i] = p[i]). I want to know if the same result can be achieved in fewer lines of code.

As an example I tried to cast pointer int* c = new int[x] to an array int b[2]

int a    = 1;
int b[2] = { 2, 3 };
int* c   = new int[b[1]];

c[0] = b[0];
c[1] = b[1];
c[2] = a;

I wanted to see what values were where, so I made a simple program to output addresses and values. The output is just below:

Address of {type: int}    &a    =       0031FEF4; a    = 1
Address of {type: int[2]} &b    =       0031FEE4; b    = 0031FEE4
Address of {type: int[2]} &b[0] =       0031FEE4; b[0] = 2
Address of {type: int[2]} &b[1] =       0031FEE8; b[1] = 3
Address of {type: int*}   &c    =       0031FED8; c    = 008428C8
Address of {type: int*}   &c[0] =       008428C8; c[0] = 2
Address of {type: int*}   &c[2] =       008428D0; c[2] = 1

Once I made sure I knew what was where I tried a few things. The first idea that came to mind was to get the address of the second element to the pointer's allocation, then replace the array's memory address with it (see the code just below). Everything I did try ultimately failed, usually with syntax errors.

This is what I tried. I really want this to work, since it would be the simplest solution.

b = &c[1];

This did not work obviously.

Edit: Solution: Don't do it! If it's necessary create a pointer to an array and then point to the array; this is pointless for any purposes I can fathom. For more detailed information see the answer by rodrigo below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all b is an array, not a pointer, so it is not assignable.

Also, you cannot cast anything to an array type. You can, however, cast to pointer-to-array. Note that in C and C++ pointer-to-arrays are rather uncommon. It is almost always better to use plain pointers, or pointer-to-pointers and avoid pointer-to-arrays.

Anyway, what you ask can be done, more or less:

int (*c)[2] = (int(*)[2])new int[2];

But a typedef will make it easier:

typedef int ai[2];
ai *c = (ai*)new int[2];

And to be safe, the delete should be done using the original type:

delete [](int*)c;

Which is nice if you do it just for fun. For real life, it is usually better to use std::vector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...