现在的位置: 首页 > 综合 > 正文

易出错的地方

2017年12月25日 ⁄ 综合 ⁄ 共 2258字 ⁄ 字号 评论关闭

一  二分查找算法
1、递归方法实现:
int BSearch(elemtype a[],elemtype x,int low,int high)
/*在下届为low,上界为high的数组a中折半查找数据元素x*/
{
  int mid;
  if(low>high) return -1;
  mid=(low+high)/2;
  if(x==a[mid]) return mid;
  if(x<a[mid]) return(BSearch(a,x,low,mid-1));
  else return(BSearch(a,x,mid+1,high));
}

2、非递归方法实现:
int BSearch(elemtype a[],keytype key,int n)
{
  int low,high,mid;
  low=0;high=n-1;
  while(low<=high) 
   {
      mid=(low+high)/2;
      if(a[mid].key==key) return mid;
      else if(a[mid].key<key) low=mid+1;
      else high=mid-1;
   }
  return -1;
}

请写出 char *p 与“零值”比较的 if 语句。(3 分)
标准答案:
if (p == NULL)
if (p != NULL)

请写出 BOOL flag 与“零值”比较的 if 语句。(3 分)
标准答案:
if ( flag )
if ( !flag )
如下写法均属不良风格,不得分。
if (flag == TRUE)
if (flag == 1 )

在C++ 程序中调用被 C 编译器编译后的函数,为什么要加 extern “C”? (5 分)
答:C++语言支持函数重载,C 语言不支持函数重载。函数被C++编译后在库中的名字
与C 语言的不同。假设某个函数的原型为: void foo(int x, int y);
该函数被C 编译器编译后在库中的名字为_foo , 而C++编译器则会产生像
_foo_int_int 之类的名字。

四、有关内存的思考题(每小题5 分,共20 分)
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
请问运行Test 函数会有什么样的结果?

答:程序崩溃。
因为GetMemory 并不能传递动态内存,
Test 函数中的 str 一直都是 NULL。
strcpy(str, "hello world");将使程序崩
溃。

//本题和常见的交换a、b的值是一样的,只有当引用 (&a,&b)作参数时才会发生值的交换,或者使用指针交换

//如第四个例子使用char** p做参数就可以了

char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test 函数会有什么样的结果?
答:可能是乱码。
因为GetMemory 返回的是指向“栈内存”
的指针,该指针的地址不是 NULL,但其原
现的内容已经被清除,新内容不可知。

void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test 函数会有什么样的结果?
答:
(1)能够输出hello
(2)内存泄漏
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL)
{
strcpy(str, “world”);
printf(str);
}
}
请问运行Test 函数会有什么样的结果?
答:篡改动态内存区的内容,后果难以预
料,非常危险。
因为free(str);之后,str 成为野指针,
if(str != NULL)语句不起作用。

五、编写strcpy 函数(10 分)
已知strcpy 函数的原型是
char *strcpy(char *strDest, const char *strSrc);
其中strDest 是目的字符串,strSrc 是源字符串。
(1)不调用C++/C 的字符串库函数,请编写函数 strcpy
char *strcpy(char *strDest, const char *strSrc);
{
assert((strDest!=NULL) && (strSrc !=NULL)); // 2分
char *address = strDest; // 2分
while( (*strDest++ = * strSrc++) != ‘/0’ ) // 2分
NULL ;
return address ; // 2分
}

(2)strcpy 能把strSrc 的内容复制到strDest,为什么还要char * 类型的返回值?
答:为了实现链式表达式。 // 2 分
例如 int length = strlen( strcpy( strDest, “hello world”) );

(3)char* p=(char*)malloc(100);
     strcpy(p,"morning");
     strcpy(p,"night");
     cout<<p;//显示night
     p所指向的都是动态地址的首地址,不会随strcpy次数的增加改变

抱歉!评论已关闭.