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"过了生命期,不在内存了
相关文档:
1.static有什么用途?(请至少说明两种)
1)在函数体,一个被声明为静态的变量在这一函数被调用过程中维持其值不变。
2) 在模块内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量。
......
由于VC编译器有函数重命名的功能所以,确定函数名有两种方式:
1.extern "C"
2.使用.def文件
这两种也可以一起使用。
下面是一个例子:
extern "C" _declspec(dllexport)int __stdcall JieCheng(int a)
{//阶乘函数。输入:正整数。输出:这个数的阶乘值
int b=1;
for(int i=1;i<=a;i++)
{
&n ......
将类成员函数用做C回调函数 提出问题: 回调函数是基于C编程的Windows SDK的技术,不是针对C++的,程序员可以将一个C函数直接作为回调函数,但是如果试图直接使用C++的成员函数作为回调函数将发生错误,甚至编译就不能通过。分析原因:普通的C++成员函数都隐含了一个传递函数作为参数,亦即“this”指针,C++通过 ......
若想在ubuntu下编译c/c++代码
首先,安装g++和gdb,可以在新立得中直接安装
若要编译c,如:
#include
<stdio.h>
int main()
{
printf("Hello,World!\n");
return 0;
}
......
#include <stdio.h>
int main ()
{
FILE *fp1;
fp1=fopen("test0.txt","rt");
if(fp1==NULL)
{
printf("can not open test0.txt\n");return 0;
&n ......