alex galdes
alex galdes

Reputation: 11

Why printing uint8_t array it shows different values?

I'm starting with c programming and I think I'm not sure about the use of unsigned variables. I know uint8_t is an unsigned 8 bit integer type, and that means that it cannot be negative, thus with all 8 bits set aside for positive numbers, this represents a number from 0 to 255. But I don't know why if I write this:

int main() {

 uint8_t value [4]; 

 printf("\nvalue:\t%" PRIu8 "", value[0]);
 printf("\nvalue:\t%" PRIu8 "", value[1]);
 printf("\nvalue:\t%" PRIu8 "", value[2]);
 printf("\nvalue:\t%" PRIu8 "", value[3]);
 printf("\n");

}

I obtain different results every time I made: ./test:

test@test:~/Desktop$ ./test

value:  48
value:  99
value:  13
value:  193

test@test:~/Desktop$ ./test

value:  176
value:  76
value:  71
value:  0

test@test:~/Desktop$ ./test

value:  64
value:  13
value:  5
value:  175

Why I get a different numbers in value[x]?

Upvotes: 1

Views: 701

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477228

It is undefined behaviour to read the value of an uninitialized variable. In other words, the rules of the C programming language do not describe or constrain how your program should behave.

To make your program well-behaved, you need to give the variable a value before reading it, for example:

uint8_t value[4] = { 3, 19, 26, 1 };

Upvotes: 4

Related Questions