在C中打印2D数组 [英] print a 2D array in C
问题描述
我想知道是否有可能像在Python中那样在C中打印2D数组.例如,如果我有 int array1 [10] [10];
,然后填写数组,则 printf(%li",array1)
似乎不起作用.在C语言中,是否有类似 printf
的东西可以将 array1
打印为 [1、2、3、4]
?在python中,它只是 print(array1)
I was wondering if it was possible to print a 2D array in C like it is in python. For example, if I have int array1[10][10];
then fill in the array then printf("%li", array1)
does not seem to work. In C, is there something like printf
that can print array1
as [1, 2, 3, 4]
? in python it would just be print(array1)
推荐答案
不幸的是,没有标准的方法可以做到这一点.打印数组的方法是:
Unfortunately, there is no standard way to do that. The way to print your array would be:
int array1[] = {1, 2, 3, 4};
size_t i = 0;
for (i = 0; i < 4; i++){
printf("%d ", array1[i]);
}
请注意,为了更正确,您可以使用 sizeof
获得数组的大小:
Note that to be more correct, you can get the size of the array using sizeof
:
int array1[] = {1, 2, 3, 4};
int i = 0;
for (i = 0; i < sizeof(array1)/sizeof(int); i++){
printf("%d ", array1[i]);
}
有人认为您应该使用 size_t
而不是 int
作为索引,因为这是 sizeof
返回的结果.
Some people would hold that you should use size_t
instead of int
for the index, since that is what sizeof
returns.
Python可以打印整个数组,因为数组不仅以一堆数字的形式存储在内存中,还以数据结构的形式存储,该数据结构还存储其他信息,例如长度的数组.
Python can print the entire array because the array is stored not just as a bunch of numbers in memory, but as a data-structure which stores other information as well, such as the length of the array.
这篇关于在C中打印2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!