Reading from STDIN

1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>
#include<unistd.h>
int main(){
int buff[100];

	int bytes = read(STDIN_FILENO, buff, 100);
	int i;
for(i = 0; i < bytes; i++)
	printf("%d \n", *((int *)(buff+ i)));

return 0;
}

whats wrong with this? It works fine with character buffer but shows garbage values with integer, although buffer of read is a void pointer..
*(buff+i) (or, alternatively, buff[i]) is the i'th integer in the array, so if you entered, for example, the string "123", read() writes 4 bytes to the beginning of the array, which is only enough to fill one int (buff[0]). buff[1]...buff[99] hold uninitialized values, and you're printing buff[0] .. buff[3] in this case.
still not working with buff[0], with input 123
i change code to
1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>
#include<unistd.h>
int main(){
int buff[100];

	int bytes = read(STDIN_FILENO, buff, 100);

	printf("%d \n", *((int *)(buff)));

return 0;
}

executed it with input 000, output = 170930224
define 'not working'? 170930224 is the expected output on a little-endian system (I get 808464394 on big-endians)
how is this ouput calcuated ? it shouldn't return 000 ? why?
read() reinterprets the array as an array of char, so each byte (0x30 for each '0' and 0xa for the endline) is stored in each of the first four bytes of the array. On a system where the size of int is 4 (almost everything today), buff[0] is then equal 0x3030300a which 808464394 decimal (or 0xa303030 for you, which is 170930224 decimal )
thanks Cubbi
Thank u
Topic archived. No new replies allowed.