C/C++ 面试题
第一题:
下面程序的输出结果?
#include <stdio.h>
#include <iostream>
void main()
{
char str1[] = "";
char str2[] = "";
const char str3[] = "abc";
const char str4[] = "abc";
const char* str5 = "abc";
const char* str6 = "abc";
char* str7="abc";
char* str8="abc";
std::cout << std::boolalpha << ( str1==str2 ) << std::endl; // 输出什么?
std::cout << std::boolalpha << ( str3==str4 ) << std::endl; // 输出什么?
std::cout << std::boolalpha << ( str5==str6 ) << std::endl; // 输出什么?
std::cout << std::boolalpha << ( str7==str8 ) << std::endl; // 输出什么?
int i;
scanf("%d",&i);
}
结果:false,false,true,true. 因为前两个的内存是在heap上分配的,当然是不同的地址;而后两个是在静态区分配的,后面的先检查前面有无该字符串,有的话,就不再分配,所以str5,str6,str7,str8地址都是相同的。
第二题:
1.检查下面程序是否有错误并写出运行结果
(1).
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
(2).
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
(3).
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory2(&str, 100);
strcpy(str, "hello");
printf(str);
}
结果:(1)程序崩溃。因为str并未被赋值,仍然是0;
(2)可能是乱码。因为"hello world"过了生命期,不在内存了
相关文档:
首先进行一个实验,分别定义一个signed int型数据和unsigned int型数据,然后进行大小比较:
unsigned int a=20;
signed int b=-130;
a>b?还是b>a?实验证明b>a,也就是说-130>20,为什么会出现这样的结果呢?
这是因为在C语言操作中,如果遇到无符号数与有符号数之间的操作,编译器会自动转化为无符号 ......
◆经典C源程序100例:http://post.baidu.com/f?kz=8618367
◆时钟的驻留程序:http://post.baidu.com/f?kz=10822377
◆数据结构暨若干经典问题和算法:http://post.baidu.com/f?kz=10922856
◆LIUXUY 磁盘系统源程序:http://post.baidu.com/f?kz=12973347
◆RLE压缩:http://post.baidu.com/f?kz=12592570
◆快速排序 ......
这个东东,蛮好玩的。其实就是读取了/proc/net/dev 文件。
struct netdev_stats {
unsigned long long rx_packets_m; /* total packets received */
unsigned long long tx_packets_m; &nbs ......