简体   繁体   中英

What would be the difference between setting a struct sockaddr_in to 0 and '\0' using memset?

I have just started off with C socket programming. I have read that 0 as an integer constant, refers to a null pointer when compared with a pointer and '\\0' refers to a null character, something that sets all the bits to 0. And, in the case concerning my question, I know I should probably be using '\\0'. But I can see a lot of implementations that uses 0 instead. What would be the difference as such? I don't wanna go with whatever that works. I can't move on till I understand why. Thanks!

There is no difference. They are equal.

There will be absolutely no difference. Please use 0 since you zeroise memory and you don't want to underscore any nature of the memory like you would do, say, when comparing either element of a char array with '\\0' to denote that you are looking for a null character .

To be more precise, ' ' is an expression which gives an integer constant which corresponds to the character specified. In this particular case, '\\0' evaluates to the same integer - 0 . So, no difference.

They are equivalent.

But it is common to use 0 when working with integers, and '\\0' when dealing with characters or bytes:

int n = 0;
char ch = '\0';

For pointers use NULL macro.

memset has following prototype:

void * memset ( void * ptr, int value, size_t num );

Although value has int type, it is being interpreted as byte value. So there is no difference.

In C, character literals such as 'x' have type int , which means '\\0' and 0 are not just numerically equal, they are 100% equivalent semantically. They are two different spellings of the same integer constant. You can only tell the difference using a construct that inspects the spelling of tokens, such as the preprocessor's # and ## operators.

(Yes, this means '\\0' is a null pointer constant.)

char is an integer type, it means that the characters you can use with the simple quotes like 'a' are in reality integer values. I invite you to look for the ascii , you'll see the link between characters and integers. You can do some easy tests with printf() :

printf("%c == %d == %c\n", 'A', 'A', 65);

You'll notice that the character '\\0' has the integer value 0 , so there is no difference, you can use 0 or '\\0' in your code, for the compiler it's the same thing. Usually, NULL is a macro for (void *) 0 wich is the value 0 casted into generic pointer (it's still the value 0 , but it will be interpreted as a pointer type).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM