Home > OS >  How to print the contents of an array in C?
How to print the contents of an array in C?

Time:08-01

I wanted to know how to print the contents of an array.

# include<stdio.h>

int main() {
    int arr[2][2];
    arr[0][0] = 1;
    arr[0][1] = 2;
    arr[1][0] = 3;
    arr[1][1] = 4;
    printf("%d", arr[1]);
    printf("%d", arr[1][0]); 
    return 0;
}

The output for the above code is coming out as unsigned int.

https://i.stack.imgur.com/A5daj.png <---- This is how the output looks like.

Please help me get the output as {3,4} and 3.

CodePudding user response:

Your first printf() statement references an array (arr[1]), so it's printing out the address of the array.

Your second printf() statement prints an array element, but since you didn't include an endline ("\n") in your first printf(), it just gets added onto the end of the first printf().

CodePudding user response:

Unless it's a string and you're using the %s conversion specifier, you can't print the contents of an entire array (or a row of a 2D array) in a single conversion. To get the output you want, you will have to print each row element individually:

printf( "{%d, %d}\n", arr[1][0], arr[1][1] );

In a more general case where you have more than two elements per row, you would use a loop (ideally in its own function):

void dispArr( int *arr, size_t num_elements, FILE *stream)
{
  fputc( '{', stream);

  for ( size_t i = 0; i < num_elements; i   )
    fprintf( stream, "%d%s", arr[i], 
      num_elements - i > 1 ? ", " : "}\n" );
}

The last bit of the fprintf statement basically says "output , after each element except the last element, which outputs }\n". In your code you'd call it as

dispArr( arr[1], 2, stdout );
  •  Tags:  
  • c
  • Related