Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Guys, basically i know the size of variables. 4/2 for int, 2 for short and 1 for char. But I just tried to find the size of a variable without sizeof().
C#
#include<stdio.h>
int main()
{
int a, b, *p1=&a, *p2=&b;
char c, d;
printf("size of a is %d\n",sizeof(a));
printf("value of p1 is:%u p2 is:%u\n",p1,p2);
printf("size of a is %d\n",(p2-p1));
return 0;
}

Using sizeof() I got 4bytes but using this which I got in many websites I got 1. What's the matter? Which one should I follow? There are many sites discussing this topic but I cannot understand!

This is my output :
CSS
size of a is 4
value of p1 is:3220066288 p2 is:3220066292
size of a is 1
Posted
Updated 31-Jul-14 1:38am
v2
Comments
Philippe Mori 2-Aug-14 8:49am    
p2 - p1 does not make any sense at all. It is undefined because they do not point to variables in the same array and thus the compiler is free to select any location it want.

By the way, substracting pointer give the number of elements between them. You have to learn basic things like that before using pointers arithmetic.
Jeevan83 2-Aug-14 10:06am    
Okay sir :)

Of course you have to trust sizeof.

You code outputs '1' because of pointer arithmetic. You should write your test this way:

C
#include <stdio.h>

int main()
{
    int a[2]; // just array items are warranted to be contiguous in memory

    char * p, *q;

    printf("using sizeof operator: %d\n", sizeof(a[0]));

    p = (char *)&a[0];
    q = (char *)&a[1];

    printf("using pointers: %d\n", (q-p));

    return 0;
}
 
Share this answer
 
sizeof returns the size in bytes: and that is absolutely what you should follow.
When you got the result:
size of a is 1
you were subtracting pointers, which returns "the number of the item the pointer points to" between them. So if you have two pointer-to-int values, and you subtract them, you get the number of int values between the two pointers, not the number of bytes.

Think about it:
C++
p1 = p1 + 1;
Should move you to the next int value: not the second byte in the first int! :laugh:
 
Share this answer
 
Comments
Philippe Mori 2-Aug-14 8:45am    
And by the way, in his case p2 - p1 is not defined as they don't point to a single array. The compiler is free to select any location for a and b variables.
OriginalGriff 2-Aug-14 9:47am    
Indeed - I have a problem with any pointer arithmetic:
p1 - p2
giving number of elements should be the same as:
p1 + (0 - p2)
and I have absolutely no idea what adding two pointers should give! Not to mention what the negative of a pointer is physically either... :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900