Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279436
  • 博文数量: 43
  • 博客积分: 2515
  • 博客等级: 少校
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-10 16:15
文章存档

2009年(2)

2008年(12)

2007年(29)

我的朋友

分类: C/C++

2007-06-09 22:33:43

静态分配的存储变量,譬如int a[10], sizeof(a)表示整个存储区域的长度,即sizeof(a) = 40;
动态分配的存储变量,譬如malloc, new等分配的存储区域,则表示指针长度,为4.
关于sizeof,本身是一个运算符,在编译的时候进行计算。另外对一个字符串数组,譬如char  buf[] = "this is a test\n",sizeof(buf)会将最后的null字节计算在内,而strlen(buf)则不计算最后的null字节,同时需要注意strlen()是一个函数,需要一次函数调用。
下面是一个示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void mem_test()
{
  // different memory allocating methods
  int a[10];
  void *b = malloc(10 * sizeof(int));
  int *c = new int[10];
  char buf1[] = "hello\n";
  char buf2[] = "hello";

  // output the size of variables
  printf("sizeof(a): %d\n", sizeof(a));
  printf("sizeof(b): %d\n", sizeof(b));
  printf("sizeof(c): %d\n", sizeof(c));
  printf("sizeof(buf1): %d\n", sizeof(buf1));
  printf("strlen(buf1): %d\n", strlen(buf1));
  printf("sizeof(buf2): %d\n", sizeof(buf2));
  printf("strlen(buf2): %d\n", strlen(buf2));
}

int main(int argc, char *argv[])
{
  // call the memory test
  mem_test();

  return 0;
}


在Linux下用g++编译通过,程序运行结果为:  (请注意buf1和buf2的区别)

sizeof(a): 40
sizeof(b): 4
sizeof(c): 4
sizeof(buf1): 7
strlen(buf1): 6
sizeof(buf2): 6
strlen(buf2): 5

阅读(1659) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~