ch2-items (Uninitialized array elements)

Chapter_2     Exercise_2-9 Exercise_2-10







items.c     K&R, p. 52         download


#include <stdio.h> // for printf(), scanf()

#define SIZE 100 // array size
// uninitialized array elements
int main()
{
int array[SIZE]; // uninitialized array of integers
int i;
unsigned n; // array size

printf("Give the array size (0 <= n <= %d): ", SIZE);
scanf("%u", &n);

if (n > SIZE)
{
printf("0 <= n <= %d\n", SIZE);
printf("Your input: n == %u\n", n);
return 1; // signal error
}

printf("You have %d item%s:\n", n, n == 1 ? "" : "s");

for (i = 0; i < n; i++)
{ // print values of uninitialized array
printf("%x%c", array[i], (i % 10 == 9 || i == n-1) ? '\n' : ' ');
} // %x hexadecimal

for (i = 0; i < n; i++)
{ // print addresses:
printf("%p%c", &array[i], (i % 5 == 4 || i == n-1) ? '\n' : ' ');
}

return 0;
}
/*
gcc items.c -o items
./items
Give the array size (0 <= n <= 100): -1
0 <= n <= 100
Your input: n == 4294967295

./items
Give the array size (0 <= n <= 100): 101
0 <= n <= 100
Your input: n == 101

./items
Give the array size (0 <= n <= 100): 0
You have 0 items:

./items
Give the array size (0 <= n <= 100): 1
You have 1 item:
0
0x7ffdb4d52c10

./items
Give the array size (0 <= n <= 100): 7
You have 7 items:
0 20 0 0 0 0 0
0x7ffcc11f3600 0x7ffcc11f3604 0x7ffcc11f3608 0x7ffcc11f360c 0x7ffcc11f3610
0x7ffcc11f3614 0x7ffcc11f3618

./items
Give the array size (0 <= n <= 100): 100
You have 100 items:
0 20 0 0 0 0 0 0 1 0
3ae75f6 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 a4531fe8 7fff 0 0
0 0 0 0 0 0 0 0 0 0
53ad8040 5573 f0b6ff 0 c2
0 a452eed7 7fff a452eed6 7fff
............................. // 100 addresses
*/









Chapter_2     Exercise_2-9 BACK_TO_TOP Exercise_2-10



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo