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
603 views
in Technique[技术] by (71.8m points)

c - convert array to two dimensional array by pointer

Is it possible to convert a single dimensional array into a two dimensional array?

i first tought that will be very easy, just set the pointer of the 2D array to the beginning of the 1D array like this:

int foo[] = {1,2,3,4,5,6};
int bla[2][3] = foo;

because i can easily create an two dimensional array like this:

int bla[2][3] = {1,2,3,4,5,6};

so the question is now, is there a way to convert it via the pointer?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can't initialise an int bla[2][3] with an int* (what foo becomes in that context).

You can achieve that effect by declaring a pointer to arrays of int,

int (*bla)[3] = (int (*)[3])&foo[0];

but be sure that the dimensions actually match, or havoc will ensue.


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

...