矩阵,指针,C * [英] Matrix, pointers, C*

查看:165
本文介绍了矩阵,指针,C *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code是这样的:

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("%d\t", *(a+i*n+j));
        putchar('\n');
    }
}

int main () {
  int matrix[3][3];

  insert (matrix); /* Function that reads Matrix from stdin */
  print_matrix(matrix, 3);
  return 1; 
}

我收到GCC错误:

I receive GCC error:

预计'诠释**,但参数的类型为INT(*)[3]

expected ‘int **’ but argument is of type ‘int (*)[3]

我读了所有相关的话题,但我还是没找到答案,我的问题,所以你把它标记为重复前请仔细阅读它。

I read all related topics but I still couldn't find answer to my question, so before you mark it as duplicate please read it.

指针不是阵列,我理解这一点。我读的地方,元素没有顺序的,在这种情况下,这可能发生:111 222 333 - > 111是第一个int数组的地址,222是第二int数组的地址,333是第三int数组的地址。但是,如果是这样的话,我不明白为什么GCC给我一个错误。

Pointers are not Arrays, I understand that. I've read somewhere that elements are not sequential, in that case, this could happen: 111 222 333 -> 111 is address of first int array, 222 is address of second int array, and 333 is address of third int array. But if this is the case, I don't understand why GCC gives me an error.

首先,我想有人来证实我,我读过是真的。然后,我真的AP preciate,如果有人能够给我回答。

First I would like someone to confirm me that what I've read is true. Then I would really appreciate if someone could give me answer.

请注意,我明白, *(A + I * N + J)是不正确的情况下内存为矩阵不是连续的。

Note that I understand that *(a+i*n+j) is incorrect in case that memory for matrix is not sequential.

最好的问候。

推荐答案

当你通过 INT [3] [3] ,该函数接收一个指向(INT *)[3] 这是一个指针的3 INT的的数组。因为数组被转换成一个指向它的第一个元素,当你把它传递给一个函数。

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');
    }

}

如果您使用C99,可以通过两个维度:

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');
    }

}

和称呼其为:

  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');
    }

}

这篇关于矩阵,指针,C *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆