同时使用在C的sizeof()运算符奇怪案件 [英] Strange case while using the sizeof() operator in C

查看:90
本文介绍了同时使用在C的sizeof()运算符奇怪案件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试中使用的C / C sizeof操作符++与此code:

 的#include<&文件ctype.h GT; / *字符类型* /
#包括LT&;&stdio.h中GT; / *标准缓冲输入/输出* /
#包括LT&;&stdlib.h中GT; / *标准库函数* /
#包括LT&;&string.h中GT; / *字符串操作* /
#包括LT&; SYS / types.h中> / *数据类型* /
#包括LT&; SYS / wait.h> / *声明等待* /
#包括LT&;&unistd.h中GT;无效的主要()
{
  所以char a [100];
  字符* DES =的malloc(100 * sizeof的(炭));
  的strcpy(DES,abcded \\ 0);
  的printf(%d个\\ N的sizeof(DES));
  的printf(%d个\\ N的sizeof(一));
  免费(DES);
}

为什么这个程序的输出:

  4
100

相对于

  100
100


解决方案
因为,尽管有许多人的,指针和数组没有在C和100%互换的断言

C ++。这其中的区别之一的一个明显的例子。

的指针的大小为4字节(或任何平台特定的大小),而不管有多少分配的内存也可能指向

的阵列的大小是所述阵列的大小。

I was testing the use of sizeof operator in C/C++ with this code:

#include <ctype.h>              /* Character types                       */
#include <stdio.h>              /* Standard buffered input/output        */
#include <stdlib.h>             /* Standard library functions            */
#include <string.h>             /* String operations                     */
#include <sys/types.h>          /* Data types                            */
#include <sys/wait.h>           /* Declarations for waiting              */
#include <unistd.h>   

void main()
{
  char a[100];
  char *des = malloc(100*sizeof(char));
  strcpy(des,"abcded\0");
  printf("%d\n",sizeof(des));
  printf("%d\n",sizeof(a));
  free(des);
}

Why does this program output:

4
100

As opposed to:

100
100

解决方案

Because, despite the assertions of many people, pointers and arrays are NOT 100% interchangeable in C & C++. This is a clear example of one of the differences.

The size of a pointer is 4-bytes (or whatever platform specific size), regardless of how much allocated memory it may point to.

The size of an array is the size of the array.

这篇关于同时使用在C的sizeof()运算符奇怪案件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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