Rak
Rak

Reputation: 53

Function passing of multidimensional array in c

#include <stdio.h>

void spiral(int a[10][10]) {
    printf("%d", a[1][3]);
}

int main() {
    int r, c, j, i;
    scanf("%d%d", &r, &c);
    int a[r][c];
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++) {
            scanf("%d", &a[i][j]);
        }

    spiral(a);
    return 0;
}

When I give a 3 x 6 array

 1   2   3   4   5   6
 7   8   9  10  11  12
13  14  15  16  17  18

The output is 14, while it should be 10

How to fix this issue?

Upvotes: 1

Views: 44

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

If you enter 3 and 6 for r and c (respectively) then the type of a is not int[10][10] (or int(*)[10] as the spiral argument really is), it's int[3][6]. The memory layout is completely different for the arrays, leading to undefined behavior.

You can solve this by passing the size along to the function, and using it in the declaration of the array:

void spiral(const size_t r, const size_t c, int (*a)[c]) { ... }

Call it like expected:

spiral(r, c, a);

As noted using int a[r][c] as argument might be easier to read and understand, but it gives a false impression that a is actually an array. It's not. The compiler treats the argument as a pointer to an array of c integers, i.e. int (*a)[c].

This makes me a little conflicted... On the one hand I'm all for making things easier to read and understand (which means it will be easier to maintain), on the other hand newbies often get it wrong and think that one can pass an array intact when in fact it decays to a pointer which can lead to misunderstandings.

Upvotes: 3

Rub3n
Rub3n

Reputation: 31

A few things are wrong: in void spiral() you ask for a 2D-array of 10*10, but you do not give that. Keep that part as a variable, so only ask the type you receive and not what you want to receive and with creating a dynamic array you should always do that with malloc or calloc and free them afterwards. This might be a bit hard at first, but when you start creating bigger programs this is a must if you have a question or do not understand the pointers in the program called (*) then ask me:

#include <stdio.h>
#include <stdlib.h>

void spiral(int **a) {
    printf("%d", a[1][3]);
}

int main() {
    int r, c, j, i;
    scanf("%d%d", &r, &c);
    int **a = malloc(r * sizeof(int*));
    for (i = 0; i < r; i++) {
        a[i] = malloc(c * sizeof(int));
    }
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            scanf("%d", &a[i][j]);
        }
    }
    spiral(a);
    for (i = 0; i < r; i++) {
        free(a[i]); 
    }
    free(a);
    return 0;
}

Upvotes: 0

Related Questions