(3)请写出char *p与“零值”比较的if语句:
答:if(p == NULL) 或 if(p != NULL)
2、头文件中的ifndef/define/endif的作用是什么?
答:避免头文件被重复引用。
3、#include
//第一个
for (i = 0; i < N; i++)
{
if (condition)
{
DoSomething;
}
else
{
DoSomething;
}
}
//第二个
if (condition)
{
for (i = 0; i < N; i++)
DoSomething;
}
else
{
for (i = 0; i < N; i++)
DoSomething;
}
答:第一个for代码的程序简洁,但是多执行了N-1次逻辑判断。第二个for代码程序不够简洁,但是效率高。
7、下面的代码的输出结果是多少?
#include
#include
void fun(int i) { if (i > 0) { fun(i / 2); } printf("%d\n", i); } int main() { fun(10); system("pause"); return 0; }
运行结果:
注意:递归的展开过程和递归的条件(递归的停止条件)。
8、编写strcpy函数
一直strcpy的原型是:char* strcpy(char *strDest, char *strsSrc);其中,strDest是目的字符串,strSrc是源字符串。
(1)不调用C/C++字符串库函数,自己编写函数strcpy;
(2)strcpy能把strSrc的内容复制到strDest,为什么还要char*类型的返回值?
(1)
答:
char *my_strcpy(char *strDest, const char* strSrc)
{
assert((strDest != NULL) && (strDest != NULL));
char *ret = strDest;
while ((*strDest++ = *strSrc++) != '\0')
{
;
}
return ret;
}
(3)便于链式访问。如:int d = strlen(strcpy(p, “hello”))。
9、下面的代码有什么问题?为什么?
char c;
c = getchar();
if (EOF == c)
{
...
}
答:会出错。因为getchar()返回的是int类型,其原型是:int getchar(),出错返回-1,成功返回其值的ASCII码。因为char的取值范围为[-2^7, 2^7-1],当返回的ASCII码不在char的取值范围,则会出错。
10、请写一个C函数,若当前系统是Big_endian的,则返回0;若是Little_endian的,则返回1。
//方式一:指针
int Check_syc(void)
{
int i = 1;
char *j = (char*)&i;
if (*j == 1)
{
return 1;
}
else
return 0;
}
//方式二:联合体
int Check_syc(void)
{
union node
{
char i;
int j;
}c;
c.j = 1;
if (c.j == 1)
{
return 1;
}
else
return 0;
}
11、类型转换。
double d = 100.25;
int x = d;
int *pInt = (int*)&d;
输出x和*pInt的值,结果是否相同?为什么?
答:不相同。因为x输出为100,但是*pInt输出的是double d的前四个字节表示的值。
12、下面的代码有什么问题?为什么?
void fun(char arr[10])
{
char c = arr[2];
}
int main()
{
char b[10] = "abcdefg";
fun(b[10]);
return 0;
}
答:
(1)调用fun(b[10])会出现越界访问,因为数组b只有10个元素,但是却访问第11个元素。
(2)编译器会发出警告,提示fun函数需要char*类型数据,而不是char类型数据。
13、下面的代码有什么问题?为什么?
#include
#include
struct student { char *name; int score; }stu,*pstu; int main() { pstu = (struct student*)malloc(sizeof(struct student)); strcpy(pstu->name, "tom"); pstu->score = 99; free(pstu); system("pause"); return 0; }
答:程序会出现异常,因为程序只给指针pstu开辟了空间。
应加上:pstu->name = (char*)malloc(sizeof(10));
14、请问运行Test函数会出现什么样的后果?为什么?
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void test()
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world!");
printf(str);
}
答:程序会出现异常。因为GetMemory不能传递动态内存,str的空间仍然为NULL,当程序运行到strcpy处时,程序就会崩溃。
15、请问运行下面代码会出现什么样的后果?为什么?
#include
#include
char *GetMemory(void) { char arr[] = "hello world!"; return arr; } int main() { char *str = NULL; str = GetMemory(); printf(str); printf("\n"); system("pause"); return 0; }
运行结果为:
答:会出现乱码,因为函数返回的是指向“栈内存的指针”,它随着函数的结束而被清除,新内容不可知。
16、请问运行下面代码会出现什么样的后果?为什么?
#include
#include
void GetMemory(char **p, int num) { *p = (char*