Matrix, pointers, C*

后端 未结 3 2042
日久生厌
日久生厌 2021-01-25 00:53

I have code like this:

void print_matrix(int **a, int n) {
    int i, j;
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++)
            printf(\"%         


        
相关标签:
3条回答
  • 2021-01-25 01:22

    If you want n to vary (and be square), it is best to allocate and use a single dimension array and multiply when you want a different row.

    int matrix[3*3];
    

    How to use it?

    matrix[row*3+col] = 5;
    

    How to pass it.

    f(int *a,int n)
    
    0 讨论(0)
  • 2021-01-25 01:24

    int** is a pointer to a pointer (pointing on an int).

    int[3][3], as a function argument, is converted to a pointer to an int array - see Is an array name a pointer?

    So the types don't match, as the compiler is telling you.

    Note: if you're doing pointer arithmetic in your function, you can pass int *a instead of int **a (by casting: print_matrix((int *)matrix, 3);. That's ugly but helps to understand what's going on - namely, a int[3][3] array is stored in memory exactly as a int[9] array, and if you're computing the int positions yourself, as you do, it will also work as a 1D array.

    0 讨论(0)
  • 2021-01-25 01:46

    When you pass int[3][3], the function receives a pointer to the (int*)[3] which is a pointer to an array of 3 int's. Because an array gets converted into a pointer to its first element when you pass it to a function.

    So adjust the function accordingly. One way is to receive it as a pointer to an array. You array indexing is wrong too. You can index just like how you would index a real the array.

    void print_matrix(int (*a)[3], int n) {
    
        int i, j;
        for(i = 0; i < n; i++) {
            for(j = 0; j < n; j++)
                printf("%d\t", a[i][j]);
            putchar('\n');
        }
    
    }
    

    If you use C99, you can pass both dimensions:

    void print_matrix(int x, int y, int a[x][y]) {
    
        int i, j;
        for(i = 0; i < x; i++) {
            for(j = 0; j < y; j++)
                printf("%d\t", a[i][j]);
            putchar('\n');
        }
    
    }
    

    and call it as:

      print_matrix(3, 3, matrix);
    

    Just to illustrate how you would access the individual "arrays":

    void print_matrix(int (*a)[3], int n) {
        int i, j;
        for(i = 0; i < n; i++) {
           int *p = a+i;
            for(j = 0; j < 3; j++)
                printf("%d\t", p[j]);
            putchar('\n');
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题