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

How to create a pointer to a multi dimensional array in C

Before anyone closes this question because there's another related one, hear me out. I've already looked at the other question and I didn't get it. I would like to create a pointer to a multi dimensional array but I don't know how. I thought I was supposed to do it like this:

int test_arr[2][4];
int *ptr_array = test_arr;

But when I do that, I get a warning saying:

incompatible pointer types initializing 'int *' with an expression of type 'int [2][4]'

I have no idea what I'm doing wrong. Can someone help me please?

question from:https://stackoverflow.com/questions/65649438/how-to-create-a-pointer-to-a-multi-dimensional-array-in-c

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

1 Reply

0 votes
by (71.8m points)

In order to do pointer arithmetic the pointer has to know the size of what it is pointing to.

int test_arr[2][4]; is equivalent to 2 elements of type int[4]. So whenever you add 1 to the pointer, it will jump the size of 4 integers. If you had int* it would increment the size of a single integer only.

Like said in the comments, what you want is: int (*ptr_array)[4] = test_arr;

I know, the syntax is a little weird, but that's how you do it.


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

...