Chinaunix首页 | 论坛 | 博客
  • 博客访问: 145152
  • 博文数量: 52
  • 博客积分: 85
  • 博客等级: 民兵
  • 技术积分: 250
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-28 09:25
文章分类
文章存档

2013年(4)

2012年(48)

分类:

2012-03-06 12:55:58

原文地址:c语言笔试小结 作者:zyhualove

c语言笔试小结                                 &nb

1.
void *p=malloc(100);
sizeof(p)=4;
---------------------指针的字节数,而不是指针指向的内容容量
2. 
void Func(char str[100])
{sizeof(str)=4;}
--------------------数组作为函数的参数进行传递时,该数组自动退化为同类型的指针
3.
char str[100];
sizeof(str)=100;
--------------------不是函数的参数时
4.
char str[]="hello";
char *p=str;
int n=10;
sizeof(str)=6;sizeof(p)=4;sizeof(n)=2;
--------------------参考上面的

注:我觉得sizeof(n)应该是4,如果在32位操作系统下
5.
#define A 3
#define B 4
#define C A+B
#define s(x) x*x
s(c)=A+B*A+B=3+4*3+4=19;
-------------------宏展开只是简单的字符串替换
6.
一组碰到最多的题,至少4次笔试的题都有它,搞得我郁闷啊
可参见林锐的《C/C++高质量编程》,很详细的解答了下面的题
(1)
void GetMemory(char *p, int num)

{

    p = (char *)malloc(sizeof(char) * num);

}
 
void Test(void)

{

    char *str = NULL;

    GetMemory(str, 100);    // str 仍然为 NULL 

    strcpy(str, "hello");   // 运行错误

}

毛病出在函数GetMemory 中。编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。如果函数体内的程序修改了_p的内容,就导致参数p的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p申请了新的内存,只是把 _p所指的内存地址改变了,但是p丝毫未变。所以函数GetMemory并不能输出任何东西。事实上,每执行一次GetMemory就会泄露一块内存,因为没有用free释放内存。
-------------------------------------形参和实参的关系,**值传递
(2)
void GetMemory2(char **p, int num)

{

    *p = (char *)malloc(sizeof(char) * num);

}
 
void Test2(void)

{

    char *str = NULL;

    GetMemory2(&str, 100);  // 注意参数是 &str,而不是str

    strcpy(str, "hello");  

    cout<< str << endl;

    free(str); 

}
----------------------------------&str是指针的地址,将指针的地址传给形参p,则p也指向str,
所以*p = (char *)malloc(sizeof(char) * num);也就是给p所指向的str分配了内存,所以正确。(个人见解)
(3)
char *GetMemory3(int num)

{

    char *p = (char *)malloc(sizeof(char) * num);

    return p;

}
 
void Test3(void)

{

    char *str = NULL;

    str = GetMemory3(100); 

    strcpy(str, "hello");

    cout<< str << endl;

    free(str); 

}
----------------------------正确
(4)
char *GetString(void)

{

    char p[] = "hello world";

    return p;   // 编译器将提出警告

}
 
void Test4(void)

{

char *str = NULL;

str = GetString();  // str 的内容是垃圾

cout<< str << endl;

}
不要用return语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡;
(5)
char *GetString2(void)

{

    char *p = "hello world";

    return p;

}
 
void Test5(void)

{

    char *str = NULL;

    str = GetString2();

    cout<< str << endl;

}
函数Test5运行虽然不会出错,但是函数GetString2的设计概念却是错误的。因为GetString2内的“hello world”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候调用GetString2,它返回的始终是同一个“只读”的内存块。
(6)
void test(void)
{
 char *p = (char *) malloc(100);

    strcpy(p, “hello”);

    free(p);        // p 所指的内存被释放,但是p所指的地址仍然不变

    …

    if(p != NULL)   // 没有起到防错作用

    {

       strcpy(p, “world”);  // 出错

    }
}


7.
程序的局部变量存在于(栈)中
程序的全局变量存在于(静态存储区)中
程序动态申请的数据存在于(堆)中

8.
二分法,冒泡排序

9.
二叉树,链表

10.
网络方面的一些:
iso 7层模型
tcp/ip 5层
tcp/udp 区别
交换机工作在 数据链路层
路由器工作在 网络层
hub工作在 物理层

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