Saturday, May 22, 2010

How to implement sizeof operator in c lanaguage?

The sizeof operator is part of the standard library,but is it possible to


write a c program or function that does the job of sizeof?

How to implement sizeof operator in c lanaguage?
as the other person said, sizeof operator is evaluated at compile time, not run time.





basically, what it does is it looks at what you declared the size of a string to be, and returns that number.





example:


char str[100];


char message[] = "hello";


int size;





strcpy(str, message);


size = sizeof(str);


//size = 100;








if you want to know the actual size of the array then you can use strlen() function.


example:





char str[100];


char message[] = "hello";


int size;





strcpy(str, message);


size = strlen(str);


//size = 5;





can you write a function to dupe sizeof()?


im not sure why you would want to since sizeof() works for what it was intended to do. you could easily dupe the strlen() function though.





int strlen(char *str)


{


int length = 0;


while (*(str + length) != NULL)


{


length++;


}


return (length);


}
Reply:The sizeof operator is not part of the C standard library. It may look like a function call, but that is not what it really is. It is a unary operator of the C language itself, just like the unary minus operator. sizeof is evaluated by the compiler at compile-time, not at run-time.





It is technically possible to implement a function that has the same functionality as sizeof, but you would need to know a lot of intricate details about your compiler, and the function would need to have at least a slightly different syntax than the sizeof operator. For example the sizeof operator may operate on primitive data type identifers, like sizeof(int), but normal functions can't do this.


No comments:

Post a Comment