gpt4 book ai didi

c - 使用指针打印矩阵的内容

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:26 25 4
gpt4 key购买 nike

这是我的作业:arrPrintMatrix(int *matrix, int m, int n): 打印内容matrix[m][n] 以表格格式显示到屏幕上。

这是我的代码:

    #include <stdio.h>
#include <malloc.h>

int main() {

void arrPrintMatrix(int *matrix, int m, int n);

int matrix[2][3] = {{5, 10 , 15}, {0, 2, 4}};
int *ptr;
ptr = &matrix[0][0];
arrPrintMatrix(ptr, 2, 3);

return 0;
}


void arrPrintMatrix(int *matrix, int m, int n) {
int i, j;

for (i = 0; i < m; i++) {
printf("\n");
for (j = 0; j < n; j++) {
printf("%d\t", matrix[i] + j);
}
}

}

但是当我运行这段代码时,第一行是 5 6 和 7,第二行是 10 11 和 12。所以 ma​​trix[i] + j 有问题。我应该如何解决这个问题?

顺便说一句,我对指针数组、malloc、函数指针感到非常困惑,所以通常我对指针感到困惑。如果您推荐一些相关的网页或视频,我会很高兴。

最佳答案

换行

        printf("%d\t", matrix[i] + j);

        printf("%d\t", matrix[i*n+j]);

更新

二维数组的内存布局在 this article 中有很好的解释。 .

关于c - 使用指针打印矩阵的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23348737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com