UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » Result of implementation for sizeof operator not matching

#1 2010-06-03 10:04 PM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Re: Result of implementation for sizeof operator not matching

Hi,

Can anyone kindly clear my doubt, this could be silly, but this is confusing me for quiet sometime.

When tried to implement sizeof operator, with below piece of code

"2"[/SIZE]

output

begin- 8285648
end -8285656           
begin-end  1 

Question : why the last result is 1 it should be 8 , is it because C does not allow arithmetic operation on addresses!

Thanks in advance

Offline

#2 2010-06-03 10:31 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,829
Website

Re: Result of implementation for sizeof operator not matching

Question : why the last result is 1 it should be 8 , is it because C does not allow arithmetic operation on addresses!

Um, it DOES allow them, and what you're seeing is the correct behavior as defined
by the language for pointer arithmetic...  When you do arithmetic on pointers, all
operations are done in units of the base size of whatever type your pointer points
to...  That's why you can step through an array with "ptr++", regardless of what type
of data the array consists of: because, it advances by "1 * sizeof (*ptr)"...  Which you
seem to semi-realize given the results of your second printf(), there...    So, knowing
that, I'm not sure how you can be surprised by the result...

Not to mention the fact that even without that pointer arithmetic behavior, just knowing
simple math rules should tell you that the result is always going to be 1: (b+1)-b is
equivalent mathematically to "(b-b)+1" or "0+1" or "1"...

What you really want to do is cast to char* in that final operation: "(char*)(b+1) - (char*)b"...
Then, since char is size 1, you'll get the results you want, since the "b+1" remains in
units of "sizeof(*b)"...

Offline

#3 2010-06-04 08:09 AM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Re: Result of implementation for sizeof operator not matching

Thanks

Offline

  • Index
  • » C
  • » Result of implementation for sizeof operator not matching

Board footer

Powered by FluxBB