Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the array?

int main() {     int my array[3][3] =     10, 23, 42,         1, 654, 0,       40652, 22, 0     };      printf("%d\n", my_array[3][3]);     return 0; } 

I am not able to get the array to print.. Any ideas why? I am a beginning programmer so any words of advice are appreciated.

like image 301
Shankar Kumar Avatar asked Mar 15 '12 19:03

Shankar Kumar


People also ask

How do I print an array line?

Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.

How do I print a single array?

This program will let you understand that how to print an array in C. We need to declare & define one array and then loop upto the length of array. At each iteration we shall print one index value of array. We can take this index value from the iteration itself.


2 Answers

What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.

for(int i = 0; i < 3; i++) {     for(int j = 0; j < 3; j++) {         printf("%d ", array[i][j]);     }     printf("\n"); }  

This will print it in the following format

10 23 42 1 654 0 40652 22 0 

if you want more exact formatting you'll have to change how the printf is formatted.

like image 102
twain249 Avatar answered Sep 25 '22 13:09

twain249


There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.

I would suggest something like this:

int index; int jdex; for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){    for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){         printf( "%d", my_array[index][jdex] );         printf( "\n" );    } } 

The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.

like image 24
Jake Avatar answered Sep 24 '22 13:09

Jake