Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

python - 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 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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...