我应该遵循操作员输出的大小还是手动执行的代码? [英] Should I Follow Sizeof Operator's Output Or Manually Executed Code?

查看:55
本文介绍了我应该遵循操作员输出的大小还是手动执行的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,基本上我知道变量的大小。 int为4/2,简称为2,char为1。但我只是试图找到没有sizeof()的变量的大小。

 #include< stdio.h> 
int main()
{
int a,b, * p1 =& a,* p2 =& b;
char c,d;
printf( a的大小是%d \ n的sizeof 的(a));
printf( p1的值为:%u p2为:%u \ n,P1,P2);
printf( a的大小是%d \ n,(p2-p1 ));
return 0 ;
}



使用sizeof()我得到了4bytes但是使用了我在很多网站上得到的1.我有什么问题?我应该遵循哪一个?有很多网站在讨论这个话题,但我无法理解!



这是我的输出:

  size     a     4  
value p1 is:3220066288 p2 是:3220066292
size a 1

解决方案

当然你 必须 信任 sizeof



你鳕鱼由于指针算术,e输出'1'。你应该这样写测试:



  #include   <   stdio.h  >  

int main()
{
int a [ 2 ]; // 只保证数组项在内存中是连续的

char * p,* q;

printf( 使用sizeof运算符:%d \ n sizeof (a [ 0 ]));

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

printf( 使用指针:%d \ n,( QP));

return 0 ;
}


sizeof 以字节为单位返回大小:这绝对是你应该的关注。

当你得到结果时:

 a的大小是1 

你正在减去指针,返回指针指向的项目编号。因此,如果你有两个指向int 的值,并且你减去它们,你得到 的数字 int 两个指针之间的值,而不是字节数。



想一想:

 p1 = p1 +  1 ; 

应该将您带到下一个 int value:不是第一个 int 中的第二个字节! :笑:


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().

#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 :

size of a is 4
value of p1 is:3220066288 p2 is:3220066292
size of a is 1

解决方案

Of course you have to trust sizeof.

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

#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;
}


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:

p1 = p1 + 1;

Should move you to the next int value: not the second byte in the first int! :laugh:


这篇关于我应该遵循操作员输出的大小还是手动执行的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆