Home > Net >  Why cant I just print the array and what are the conditions to avoid a loop?
Why cant I just print the array and what are the conditions to avoid a loop?

Time:09-30

I wrote a program that changes the order of any given array and now I wanted to print it. Often, I just use a for-loop for integers, chars and all the other types, because it looks like that this works every time. Nevertheless, I am curious about the short version and I would like to know when I can use it. At the moment it just prints stuff from a random place.

#include <stdio.h>

int main() {
    int array1[] = { 4, 5, 2, 7, 5, 3, 8 };
    int laenge = sizeof(array1) / sizeof(array1[0]);
    printf("%d\n", laenge);
    int array2[laenge];
    
    for (int i = 0; i < laenge; i  ) {
        array2[laenge - 1 - i] = array1[i];
    }
    
    printf("%d\n\n", array2);
    for(int j = 0; j < laenge; j  ) {
        printf("%d", array2[j]);
    }
    return 0;
}

CodePudding user response:

When you say,

Nevertheless, Im curious about the short version and I would like to know when I can use it.

, I take you to be asking about this:

    printf("%d\n\n", array2);

The short answer is "never".

A longer answer is that

  1. the C standard library does not provide any functions for producing formatted output of whole arrays (except the various flavors of C strings as a rather special case), and in particular, printf does not provide such a facility; and

  2. the particular printf call you present has undefined behavior, and even on its face does not mean what it sounds like you think it means. It is attempting to print a pointer (to the first element of array array1) as if that pointer were an int.

CodePudding user response:

Often, I just use a for-loop for integers, chars and all the other types, because it looks like that this works every time.

If the loop uses the correct iteration and the body converts the array contents appropriately to a valid stream, it should work every time.

Nevertheless, I am curious about the short version and I would like to know when I can use it.

The only type of array for which printf has built-in support is arrays of char. If the array is null terminated, %s will print it, if it is not, %.*s can be used and the number of elements must be passed before the array pointer as an int argument.

Other types are not supported by default. Using a loop is the only portable solution.

At the moment it just prints stuff from a random place.

printf("%d\n\n", array2) has undefined behavior because %d expects an int argument and you pass a pointer to int. printf will retrieve an int value from the place where the code would have provided an int argument, array2 is passed as a pointer, possibly in a different place and with a different representation, so the output if any will be meaningless and the program could misbehave in other unpredictable ways.

  • Related