一道极易混淆的笔试题

摘自:http://www.52coder.net/archives/120.html

C/C++ code

1、 char test[] = {0x01,0x02,0x03}; int a = strlen(test); int b = sizeof(test);
 
2、 char test[] = {0x01,0x00,0x03}; int a = strlen(test); int b = sizeof(test);
 
3、 char test[20] = {0x01,0x02,0x03}; int a = strlen(test); int b = sizeof(test);
 
4、 char test[20] = {0x01,0x00,0x03}; int a = strlen(test); int b = sizeof(test);

以上题目中的a、b分别是多少,看到题目的时候不要机械的复制黏贴到编译器中

答案:
1、
char test[] = {0×01,0×02,0×03};
int a = strlen(test); // 未知,不知道null在哪里,,看栈上的内容,十六进制下null为0×00
int b = sizeof(test); // 3
关于第一点这里需要解释一下,有关于C/C++中变量作用域和存储类型,系统为不同存储属性的变量分配了不同类型的内存空间,C++程序中的变量分为三种内存分配方式:静态分配、自动分配和动态分配。一个程序运行时,系统为每个程序开辟了三块絮语,分别是固定的鼎泰存储区,栈的活动存储区和堆。

静态分配是指在静态存储区内为变量分配内存空间,编译时就分配了内存地址,程序开始执行时就开始占用内存,程序结束时才释放内存。

自动分配是指在栈中为变量临时分配内存空间,程序运行时,在变量作用域开始时有系统自动为变量分配内存,在作用域结束后释放内存。

动态分配是指在堆中为变量分配内存空间,堆使用静态存储区和栈之外的部分内存,动态分配是一种由程序本身控制内存的分配方式,在程序运行后,利用new()和delete()运算符进行内存的分配和释放。

strlen()

Get the length of a string, using the current locale or a specified locale.Each of these functions returns the number of characters in str, excluding the terminal NULL. No return value is reserved to indicate an error, except for _mbstrlen, which returns ((size_t)(-1)) if the string contains an invalid multibyte character.

2、

char test[] = {0x01,0x00,0x03};
 
int a = strlen(test); // 1
 
int b = sizeof(test); // 3

3、

char test[20] = {0x01,0x02,0x03};
int a = strlen(test); // 3,其余的被初始化成0,即null
int b = sizeof(test); // 20

4、

char test[20] = {0x01,0x00,0x03};
int a = strlen(test); // 1
int b = sizeof(test); // 20

电脑前的你做对答案了吗?

本文出处 我爱程序员 www.52coder.net转载请注明出处

posted @ 2012-10-15 22:15  emmac  阅读(230)  评论(0)    收藏  举报