hello!
Am a beginner on programming in c, i would like to know the uses of sizeof operator
hello!
Am a beginner on programming in c, i would like to know the uses of sizeof operator
Well, it tells you how many bytes an object contains (with no assumptions of the number of bit in a byte, mind you), so for instance making a "shallow" copy of an object (ie: bitwise; no accounting for the values referred to by pointers of a data structure), or generic bit-twiddling algorithms for integers of arbitrary size, etc.
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
The most common use is as an argument to malloc
Code:int main(void) { int *x = malloc(sizeof *x); *x = 1234; printf("x is %d\n", *x); return 0; }
I know that's just a trivial demonstrative snippet, but for the sake of good programming habits examples of malloc should always be followed up with an appropriate number of free calls.
I'll go ahead and amend that for the OP:
Code:int main(void) { int *x = malloc(sizeof *x); *x = 1234; printf("x is %d\n", *x); free(x); return 0; }
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
True. Actually to be correct you must also handle failed memory allocations as well
Code:int main(void) { // allocate x int *x; if ((x = malloc(sizeof *x)) == NULL) { fprintf(stderr, "Failed to allocate memory"); return 1; } // do something with x *x = 1234; printf("x is %d\n", *x); // clean up free(x); return 0; }
One other common use is to get the number of elements in an array. This can be used like so:
Code:int x[10]; size_t i; for (i = 0; i < sizeof x / sizeof x[0]; i++) x[i] = 1;
i dont believe in competition in da field of cboard posts, u see, i believe in a collection of posts each 2 be admired for der own personal statement. when in doubt, ask Willy!