Reputation: 659
Am I forced to use loops and realy long lines or is something like this possible in c?
int a[5] = {1, 2, 3, 5, 8};
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]); // this is ok but
printf("%d %d %d %d %d\n", a); // is this somehow possible??
I am asking if there is a way.
Upvotes: 1
Views: 60
Reputation:
This line:
printf("%d %d %d %d %d\n", a);
is actually just plain undefined behavior because 1) the format string expects 5 arguments, but you only provide one and 2) it expects a %d
but you provide an array.
There isn't a built-in way to output the contents of an array, except for character arrays. For %s
, it will print up to the terminating null byte or up to the maximum amount of characters specified by the precision. Even if you were able to provide the size of the array, the printf specification doesn't support it. Just use a loop.
Upvotes: 0
Reputation: 311018
Thy the following trick
#include <stdio.h>
int main(void)
{
struct { int a[5]; } A = { { 1, 2, 3, 5, 8 } };
printf( "%d %d %d %d %d\n", A.a[0], A.a[1], A.a[2], A.a[3], A.a[4] );
const char *f = "%d %d %d %d %d\n";
printf( f, A );
return 0;
}
The output is
1 2 3 5 8
1 2 3 5 8
Upvotes: -1
Reputation: 134336
Point 1.
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);
Perfectly ok, but think of the horror when you have, say 10,000 elemnts.
Point 2.
printf("%d %d %d %d %d\n", a);
Problem with basic concept. You did not supply enough values to print.
Baseline: Stick to loops while printing array elements one by one.
Upvotes: 3