[英]C passing 2D array to function, printing results
I am trying to print a 2D array by passing it to a function, but I got weird results. 我试图通过将2D数组传递给函数来进行打印,但结果却很奇怪。 Here is my code.
这是我的代码。
#include <stdio.h>
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray(b);
return 0;
}
void printArray(int (*ptr)[3])
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *((*ptr+i)+j));
}
printf("\n");
}
}
However, the output is 但是,输出是
1 2 3
2 3 4
I think it is something to do with my 'j' variable but I can't seem to pinpoint it. 我认为这与我的'j'变量有关,但我似乎无法查明。 Please help.
请帮忙。
您需要将i乘以3才能加上j ...
printf("%d\t", *((*ptr+(i*3))+j));
You need to apply the addition operator before using the dereference operator. 您需要在使用取消引用运算符之前应用加法运算符。 You need to use parenthesis as the dereference operator(
*
) has higher precedence than the addition operator( +
). 您需要使用括号,因为取消引用运算符(
*
)的优先级高于加法运算符( +
)。
So, this 所以这
printf("%d\t", *((*ptr+i)+j));
should be 应该
printf("%d\t", *((*(ptr+i))+j));
or better 或更好
printf("%d\t", ptr[i][j]);
Also, you need to move the function printArray
before main
or provide a function prototype before main
like: 另外,您需要将函数
printArray
移到main
之前,或者将函数原型提供到main
之前,例如:
void printArray(int (*ptr)[3]);
Abandoning indexes in favor of pointers, assuming matrix is stored by rows (whic is normally the case): 假设矩阵按行存储(通常是这种情况),则放弃使用指针而使用索引:
#include <stdio.h>
void printArray(int *);
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int*)b);
return 0;
}
void printArray(int *ptr)
{
int i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", *ptr++);
}
printf("\n");
}
}
Outputs: 输出:
1 2 3
4 5 6
printArray
can take nb_column
nb_line
param and deal with all sort of 2D array printArray
可以采取nb_column
nb_line
PARAM和处理所有类型的二维数组的
#include <stdio.h>
static void printArray(int *ptr, int nb_columns, int nb_lines)
{
int i, j;
for(i = 0; i < nb_lines; i++)
{
for(j = 0; j < nb_columns; j++)
{
printf("%d\t", *(ptr++));
}
printf("\n");
}
}
int main()
{
int b[2][3] = {{1,2,3},{4,5,6}};
printArray((int *)b, 3, 2);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.