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

c - Passing two-dimension array as a parameter

I have encountered a problem with passing two dimensional arrays to other function as parameter. It was not working when I tried as below.

#include <stdio.h>

int display(int **src) {
    printf("%d", src[0][1]);
}

int main() {
    int arr[2][2] = {{1,2}, {3,4}};
    display(arr);
    return 0;
}`

It raises segmentation fault error. So I changed the display function as below

int display(int src[][3]) {
    printf("%d", src[0][1]);
}

I am not sure why first case raises error. Please help me to understand deeply about this case.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
int display(int **src) {
    printf("%d", src[0][1]);
}

you can not do that because the compiler doesn't know the dimensions (rows and columns), in other words: C doesn't use introspection.

Instead:

int display(int src[][2]) {
    printf("%d", src[0][1]);
}

or if you prefer

int display(int (*src)[2]) {
    printf("%d", src[0][1]);
}

Note that you don't need to specify the first dimension, C is able to calculate the position based on the offset: (sizeof(int) * cols)

Also, you promised to return something from the function, if you don't want to return a value use:

void display(int (*src)[2]) {

Finally, as pointed out by @Scheff in comments, your original array haves 2 columns, receiving 3 will break the indexing in the receiver.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...