Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How big is an integer?

Tags:

c

What is the correct way to work out how many bytes an int is? and how do I write an int to a file descriptor?

Here is a mock code sample which might make clear what I am trying to achieve:

char *message = "test message";
int length = strlen(message);
int fd = open(file, O_CREAT|O_RDWR);
write(fd, length??, ??); // <--- what goes here
write(fd, message, length);

I dont care about platform independence and byte order, just that it can compile on as many platforms as possible.

like image 988
Jay Avatar asked Dec 12 '22 18:12

Jay


1 Answers

sizeof(length) goes in the field.

It is preferable over using sizeof(int) in case you ever change the type of length in the future.

sizeof expresses the, well, size of a data type in multiples of sizeof(char), which is always 1.

like image 68
逆さま Avatar answered Jan 04 '23 23:01

逆さま