开发者

print a 2D array in C

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 wor开发者_如何学Pythonk. 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]);
}

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

Some people would hold that you should use size_t instead of int for the index, since that is what sizeof returns.

EDIT: 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.


More specifically, when printing a 2D array in C, you'll need to implement a double for-loop:

//in pseudo code

  1. assume array is called myArray
  2. get the width of the array, call it j
  3. get the length of the array, call it k
  4. for(a = 0; a < j; a++){
  5. ....for(b = 0; b < k; b++){
  6. ........printf("%d", myArray[a][b]);
  7. ....}
  8. }


The straightforward answer is "no" ... you have to code it yourself. And it isn't possible to write a general dumper routine in C because the size of arrays is not known.


   // Int array [10][10];
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
Print("%d",array[i][j]);
}
}

Using this code you can print 2D array in C

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜