Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...