(15分)下面一段代码,想在调用f2(1)时打印err1,调用f2(2)时打印err4,但是代码中有一些问题,请做尽可能少的修改使之正确。
1 static int f1(const char *errstr, unsigned int flag) {
2 int copy, index, len;
3 const static char **__err = {“err1”, “err2”, “err3”, “err4”};
4
5 if(flag & 0x10000)
6 copy = 1;
7 index = (flag & 0x300000) >> 20;
8
9 if(copy) {
10 len = flag & 0xF;
11 errstr = malloc(len);
12 if(errstr = NULL)
13 return -1;
14 strncpy(errstr, __err[index], sizeof(errstr));
15 } else
16 errstr = __err + index;
17 }
18
19 void f2(int c) {
20 char *err;
21
22 swtch(c) {
23 case 1:
24 if(f1(err, 0x110004) != -1)
25 printf(err);
26 case 2:
27 if(f1(err, 0x30000D) != -1)
28 printf(err);
29 }
30 }
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DEBUG
static int f1( char **errstr, unsigned int flag) //change char *errstr -->char **errstr
{
int copy, index, len;
//int i=0;
// static char **__err = {"err1", "err2","err3","err4"}; //此行换为下行
static char __err[4][10] = {"err1", "err2","err3","err4"};
if(flag & 0x10000) copy = 1;
else copy=0; //add 如果不加的话 copy 没有初始化
index = (flag & 0x300000) >> 20;
#ifdef DEBUG
printf("copy %u index:%u\n",copy,index);
#endif
if(copy)
{
len = flag & 0xf;
*errstr =(char*) malloc(len+1);
if( (*errstr) == NULL ) //change = ---> ==
return -1;
strncpy(*errstr, __err[index-1], len); //change -1 sizeof(errstr)=4 -->len
}
else
{
//*errstr = __err+index; appear :
//cannot convert char (*)[10] to char * in assignment
*errstr = __err [index];
}
return 0;
}
void f2(int c)
{
char *err;
switch(c)
{
case 1:
if(f1(&err, 0x110004) != -1)
printf("%s\n",err);
break; //add
case 2:
if(f1(&err, 0x30000D) != -1) //change f2 ->f1
printf("%s\n",err);
break; //add
}
free(err); //add
}
int main(int argc,char *argv[])
{
f2(1);
f2(2);
return 0;
}
看来 这类改错题 还是不能 小瞧的。
|
阅读(2603) | 评论(0) | 转发(0) |