how to know size of int without sizeof [duplicate] - c

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
size of a datatype without using sizeof
This is question asked in a C interview I wanted to know what is the correct logic for this
If you are not having a sizeof operator in C, how will you get to know
the size of an int ?

Use an array[*]:
int a[2];
int sizeof_int = (char*)(a+1) - (char*)(a);
Actually, due to a note in the section on pointer arithmetic, you don't even need an array, because for the purposes of pointer arithmetic an object behaves like an array of size 1, and an off-the-end pointer is legal for an array:
int a;
int sizeof_int = (char*)((&a)+1) - (char*)(&a);
[*] By which I mean, "a solution to the puzzle posed is to use an array". Don't actually use an array, use sizeof!

One way would be to calculate the address difference between two consecutive int variables.

I think of two ways. One is to print '-1' as a unsigned value and deduce the size basing on the number that is printed. Second is this:
#include <stdio.h>
int size()
{
int a = 1;
int size = 1;
while(a<<=1)
size++;
return size;
}
int main(int argc, char** argv)
{
printf("Size of int: %d\n", size());
return 0;
}

Declare int, init it to -1. Repeatedly '<<1' it until it's 0. Number of shifts requried = size in bits. '<<3' for size in bytes.
Rgds,
Martin

Related

c sizeof function of an array in a function is always four bytes despite the number of array elements [duplicate]

This question already has answers here:
"sizeof" to know the size of an array doesn't work in a function in C [duplicate]
(2 answers)
Closed 6 years ago.
When I print the (size of the array/size of the the first element), I get the right answer, but when I do the same thing in the function, I get the size of the array to be four and the size of the first element of the array to be four hence the division is always one.
#include<stdio.h>
int sizer(int *);
int main()
{
int num;
printf("Please an index: ");
scanf("%d",&num);
int array[num];
int size = sizer(array); //function to calculate array length
/*answer is always 4*/
printf("%d\n", size);
/*answer is correct*/
printf("%d\n", sizeof(array) / sizeof(array[0]));
return 0;
}
/*function to calculate array length*/
int sizer(int *array)
{
return sizeof(array) / sizeof(array[0]);
}
sizeof is not a function called at runtime, even though it looks like one. It is a feature of the compiler. It looks at a data object and replaces the sizeof() expression with a constant.
int arr[10];
int size = sizeof(arr)/sizeof(int);
This works because the compielr can see how big arr is. arr is a statically sized array here. Both sizeof expressions are replaced with the appropriate values.
int arr[10];
int size = sizer(arr);
....
int sizer(int array[]) {
return (sizeof(array)/sizeof(int));
}
This doesn't work. In sizer, array looks like an array but arrays passed in as parameters are actually just pointers to the array type. So sizeof(array) is equivalent to sizeof(int *)
scanf("%d",&num);
int arr[num];
int size1 = sizeof(arr)/sizeof(int);
int size2 = sizer(arr);
....
int sizer(int array[]) {
return (sizeof(array)/sizeof(int));
}
Here, size1 works but size2 doesn't. The creation of arr is actually allocated like this:
int arr_sizeof = sizeof(int)*num;
int *arr = alloca(arr_sizeof);
Then later on, sizeof(arr) is quietly replaced with arr_sizeof. But the compiler can only do this in the same scope that arr is created, because when arr is passed to sizer it's just converted to an int * again, so the size information is not carried over. sizer fails for thet same reason, arrays in function parameters are just passed along as simple pointers.
When you pass an array to a function you are really just passing a pointer to the first element, so in the body of sizer, the parameter array is just a pointer to int. Your function correctly returns sizeof(int*)/sizeof(int) (which is 2 rather than 4 on my machine), though this is probably not what you want. There really isn't any way for a function in C to compute the length of a passed array, which is why it is standard in C to pass the number of elements in an array as one of the parameters in any function which takes an array parameter.

Char array sizeof() method [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 5 years ago.
Complete example:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d\n", arrSize); // 2 (wrong?!)
}
int main (int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
int arrSize = (int)(sizeof(point) / sizeof(point[0]));
printf("%d\n", arrSize); // 3 (correct :-) )
test(point);
return 0;
}
Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?
When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.
If you need the function to know the size of the array, you should pass it as a separate parameter:
void test(int arr[], size_t elems) {
/* ... */
}
int main(int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
/* ... */
test(point, sizeof(point)/sizeof(point[0]));
/* ... */
}
Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.
Because array is decayed to a pointer when passed as function argument, so sizeof gives you 4 and 8 for 32- and 64-bit platforms respectively.
Also, it's important to understand that sizeof is evaluated at compile time. Since that's the case, it doesn't make sense to expect different output in test() depending on what was passed in. The sizeof calculation was done when the function was compiled.
Because, when it's passed, only the pointer to array is actually being passed.
Your question is also answered at The C Programming FAQ. Question 6.21.
Because in C, C++, and Objective-C, functions cannot actually have array parameters. They only can have parameters that look like array parameters, but they aren't. In your example,
void test(int arr[])
the compiler sees "there is a parameter that looks like an array of int", and it replaces that parameter with a "pointer to int". So the function that you wrote is absolutely, one hundred percent, identical to
void test (int* arr)
Therefore, inside the function sizeof (arr) will give you the size of a "pointer to int".
Because sizeof() does NOT tell you the size of an array in C. It does something completely different.
sizeof C++ reference

Why is the sizeof function returning to different values for the same array? [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 9 years ago.
Consider this piece of code (or just copy/paste and run it):
#include <stdio.h>
int array[] = {1, 2, 3, 4, 5, 6, 7};
int my_put(int *array)
{
printf("Size of array %lu\n", sizeof(array));
return 0;
}
int main(int argc, char **argv)
{
printf("Size of array %lu\n", sizeof(array));
my_put(array);
return 0;
}
My question is: How come that the sizeof function returns two different values? Why is the size 28 in the main function and 8 in the my_put function?
Because in my_put(), array is an int * pointer, not an array. Your parameter shadows the global array variable. It might be clearer if you rewrite my_put to look like this:
int my_put(int *a)
{
printf("Size of array %zu\n", sizeof array);
printf("Size of a %zu\n", sizeof a);
return 0;
}
This new function doesn't confuse two variables named array. I also fixed it to use the z format specifier for size_t types.
Plenty more at the comp.lang.c FAQ, section 6, Arrays and Pointers, particularly Question 6.21 for your case.
In my_put name array is shadowed by your func's arg and its size is 8 (since it is a pointer). In main you get size of your 'real' array. That's all
In function my_put , array is pointer and its size is of the size of int *. Read C-FAQ 6.21.
Because its not the same "array". You have two arrays here -- the global variable "array" and the argument "array" to my_put. Now the second one is actually a pointer that points at the first one, but its a distinct variable with a different type (int pointer vs int array), so it has a different size.

But the sizeof() operator doesn't work on pointer but works on the array name. Why is it so? [duplicate]

This question already has answers here:
Stack pointer difference for char pointer and array
(1 answer)
C pointers and arrays/ 'sizeof' operator [duplicate]
(2 answers)
Closed 9 years ago.
Hi i was doing this exercise and wanted to get the size of array after i pass the pointer to the array to the function:
But the sizeof() operator doesn't work on pointer but works on the array name. Why is it so?
Is this any way i could get the size of the array on the findPut function?
#include <stdio.h>
//global vars
int i,j;
//functions prototypes
void findPut(int *, int);
int main(void){
int ins=4;
int arr[10]={1,2,3,5,6,7,8};
printf("%d\n",sizeof(arr)); //gives 40
int *ap=arr;
printf("%d\n",sizeof(*ap)); //gives 4 instead of 40 why?? if ap and arr the same thing
findPut(ap, ins);
return 0;
}
//functions
void findPut(int *p, int n){
//vars
//getting size of array
int size= sizeof(*p);
//sizeof(int);
printf("%d\n",size); //gives 4 but expected 40????
}
When you dereference *p you get an int, so it returns 4 (which is the size of int on your platform).
Because, sizeof(*ap) means sizeof(arr[0]); since array is of type int, sizeof(int), since in your system configuration, int is of size 4 you got the result as 4.
You can try it your self by printing the value of *p, you will get the value of arr[0].
Let int *p be a pointer and int arr[10]
Please note that:
Arrays and Pointers are not equivalent.
sizeof operator is a compile time operator.
sizeof(arr), evaluates to 10*sizeof(int), that is 10*4=40 in your case.
When you dereference p (getting the value that p points to), it doesn't give you whole array, but one unit of
your array that is an int so, *p means arr[0]. sizeof(arr[0]) is
4 (in your case) that's obvious.
When you use sizeof(p), it will give you the size of the pointer in your machine.
In my machine it is 8.
main function's return type should be int always. It has to retport operating system the exit status of the program. If you use void it might return random garbage.
The example demonstrate the issue:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *p=NULL;
int arr[10]={10,1,2,3,5,6,7,8,9,10};
p=arr;
printf("values: arr[0]=%d *p= %d\n\n",arr[0],*p);
printf("sizes : sizeof(arr[0])=%lu, sizeof(*p)= %lu sizeof(int)=%lu\n\n",sizeof(arr[0]),sizeof(*p),sizeof(int));
printf("Sizeof pointer p: %lu \n\n",sizeof(p));
printf("Sizeof arr: %lu \n\n",sizeof(arr));
printf("Pointing p to the first byte of 100 byte sequence\n\n");
p=malloc(100);
printf("Though p is pointing 100 byte block, sizeof(p)=%lu",sizeof(p));
return 0;
}
Essentially, sizeof evaluates the sizeof type but not the sizeof type it points to.
Thank you, i do appreciate your knowledge but is there any way i could
find the size of array inside another function( not the one where i
define the array).
You can't in my IMHO! You have to pass the size along with the array.
Example:
int main(){
int arr[10]={10,1,2,3,4,5};
printf("Length of array: %lu",findLength(arr,sizeof(arr)));
return 0;
}
size_t findLength(int *p,int size){
return size/sizeof(*p);
}
You have an int array and an int pointer:
int arr[10] = {1,2,3,5,6,7,8};
int* ap;
ap = arr;
In C, the expression arr is equivalent to &arr[0]. It stands to reason, then, that *ap is equivalent to arr[0], which is an int, which for your binary has a size of 4.
You also need to understand that arrays and pointers aren't the same thing. You may have been confused by the fact that arrays and pointers are often used interchangeably in the sense that a pointer can store the address of the beginning of an array (its first element, in other words) and navigate the consecutive addresses as if it had the actual array passed to it.

measuring the number of tuples of the int array [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Array length counting anomaly
(4 answers)
Closed 8 years ago.
I use a macro to get the number of the elements of an integer array, and I could get the right result of the number of the integer array in the main function, but I got the wrong answer if I use a getData function and send the pointer of the integer array as a parameter. I want to know why I got this wrong answer. Thank you!
the code of my program as follow:
#include <stdio.h>
#define LENGTHOFINTARRAY(intArray) ((int)(sizeof(intArray)/sizeof(int)))
int main (int argc, char *argv[])
{
int a[] = {5,8,9,4,11,7,15,25,1};
int getData(int *data);
printf("%d\n", LENGTHOFINTARRAY(a));
getData(a);
return 0;
}
int getData(int *data)
{
int i = 0;
for(i; i < LENGTHOFINTARRAY(data); i++)
{
printf("%d, %d\n", LENGTHOFINTARRAY(data), data[i]);
}
return 1;
}
and the result of my program is:
9
1, 5
I use gcc as my compiler.
The type of int* data is just int* and not int[9] like in main. The size of int* is is the size of any other pointer (4 or 8 bytes usually). There is no way to get the size of an array from the pointer.
And since arrays can't be passed by value in C (unless inside a struct or something) you have to pass the length of the array.
getData() sees data as an int*. It does not know how long it is.
You cannot determine the size of an array that is passed as a pointer to a function.
As you have defined
int a[] = {5,8,9,4,11,7,15,25,1};
int getData(int *data);
printf("%d\n", LENGTHOFINTARRAY(a));
getData(a);
so when you call "getData(a)" then it means you are passing the address of the very first element as &a[0];
so inside you function getData() as
int getData(int *data)
{
int i = 0;
for(i; i < LENGTHOFINTARRAY(data); i++)
{
printf("%d, %d\n", LENGTHOFINTARRAY(data), data[i]);
}
return 1;
}
the data is just a pointer to integer & it gets the pointer or address of the a[0];
so your macro now sees data as pointer to int. which causes the result as u have gotten.

Resources