1

Why does printf show different output for 4 different char[] variables if they all have the same value?

Here is my code:

#include <stdio.h>
#define     MAX 1000

main()
{
    char w[MAX];
    char x[MAX];
    char y[MAX];
    char z[MAX];

    printf("w: %s\n", w);
    printf("x: %s\n", x);
    printf("y: %s\n", y);
    printf("z: %s\n", z);
}

Here is the output:

gcc test.c -o test && ./test
test.c:4:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
    4 | main()
      | ^~~~
w: 
x: ��<��
y: 
z: S�td
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Pusher91
  • 35
  • 6
  • 1
    This is not related to the warning you posted, but none of the variables are initialized, so it's incorrect to say they have the same values. Actually this code has undefined behavior. Specifically for printing with `%s` the variables should contain zero terminated strings. – wohlstad Aug 12 '22 at 16:52
  • `w, x, y, z` are not string, as you trying to handle them in `printf` with `%s`. char and int have the same byte value (I think i s that they call them). – Joel Aug 12 '22 at 16:53
  • BTW your specific warning is because you didn't mention the return type for `main()` which should be `int`. – wohlstad Aug 12 '22 at 16:54
  • `if they all have the same value?` How do you know what _value_ they have? – KamilCuk Aug 12 '22 at 16:56
  • Try `char w[MAX] = "hello";` You declared arrays, but you forgot to put something into those arrays. Another method for putting something into the array: `char x[MAX]; strcpy(x, "world");` – user3386109 Aug 12 '22 at 17:01
  • 1
    You need to understand and fix that warning message. – n. m. could be an AI Aug 12 '22 at 17:07

1 Answers1

1

Why does printf show different output for 4 different char[] variables if they all have the same value?

The arrays do not have "the same value". You have uninitialized character arrays with automatic storage duration that can contain any indeterminate values

char w[MAX];
char x[MAX];
char y[MAX];
char z[MAX];

So using them in the calls of printf

printf("w: %s\n", w);
printf("x: %s\n", x);
printf("y: %s\n", y);
printf("z: %s\n", z);

invokes undefined behavior.

If you would declare the arrays before the function main then they would be zero-initialized as having static storage duration. In this case they will contain empty strings and you will get the output like

w:
x:
y:
z:

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335