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

c - Why does 2 dimension array passing to function requires its size?

Inspired this quiestion .

Why does -

void display(int p[][SIZE]) // allowed

and

void display(int p[][]) // not allowed

?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because arrays decay to pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer.

Here is a longer explanation: when you write this

p[index]

the compiler performs some pointer arithmetic to find the address of the element that it needs to reference: it multiplies index by the size of p's element, and adds it to the base address of p:

address = <base address of p> + index * <size of p's element>

When you try passing an array like this, p[][], the compiler knows only the base address of p, but not the size of its element. It is in order for the compiler to know the size of p's element that you need to provide the cardinality of the second dimension.


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

...