1、 找錯
void test1()
{
char string[10];
char* str1="0123456789";
strcpy(string, str1);
}
表面上並且編譯都不會錯誤。但如果string陣列原意表示的是字串的話,那這個賦值就
沒有達到意圖。最好定義為char string[11],這樣最後一個元素可以儲存字串結尾符
;
void test2()
{
char string[10], str1[10];
for(int I=0; I<10;i++)
{
str1[I] =a;
}
strcpy(string, str1);
}
strcpy使用錯誤,strcpy只有遇到字串末尾的才會結束,而str1並沒有結尾標誌,
導致strcpy函式越界訪問,不妨讓str1[9]=,這樣就正常了。
void test3(char* str1)
{
char string[10];
if(strlen(str1)<=10)
{
strcpy(string, str1);
}
}
這又會出現第一道改錯題的錯誤了。strlen(str1)算出來的值是不包含結尾符的,如
果str1剛好為10個字元+1結尾符,string就得不到結尾符了。可將strlen(str1)<=10改為
strlen(str1)<10。
2、找錯
#define MAX_SRM 256
DSN get_SRM_no()
{
static int SRM_no;
int I;
for(I=0;I
{
SRM_no %= MAX_SRM;
if(MY_e==IDLE)
{
break;
}
}
if(I>=MAX_SRM)
return (NULL_SRM);
else
return SRM_no;
}
SRM_no沒有賦初值
由於static的.宣告,使該函式成為不可重入(即不可預測結果)函式,因為SRM_no變數放
在程式的全域性儲存區中,每次呼叫的時候還可以保持原來的賦值。這裡應該去掉static聲
明。
3、寫出程式執行結果
int sum(int a)
{
auto int c=0;
static int b=3;
c+=1;
b+=2;
return(a+b+c);
}
void main()
{
int I;
int a=2;
for(I=0;I<5;i++)
{
printf("%d,", sum(a));
}
}
8,10,12,14,16
4、int func(int a)
{
int b;
switch(a)
{
case 1: b=30;
case 2: b=20;
case 3: b=16;
default: b=0;
}
return b;
}
func(1)=0,因為沒有break語句,switch中會一直計算到b=0。這是提醒我們不要忘了bre
ak。
5、int a[3];
a[0]=0; a[1]=1; a[2]=2;
int *p, *q;
p=a;
q=&a[2];
a[q-p]=a[2]=2;
6、定義 int **a[3][4], 則變數佔有的記憶體空間為:
此處定義的是指向指標的指標陣列,對於32位系統,指標佔記憶體空間4位元組,因此總空間為
3×4×4=48。
7、編寫一個函式,要求輸入年月日時分秒,輸出該年月日時分秒的下一秒。如輸入2004年
12月31日23時59分59秒,則輸出2005年1月1日0時0分0秒。
void NextMinute(int *nYear,int *nMonth,int *nDate,int *nHour,int *nMinute,int
*nSecond)
{
int nDays;
(*nSecond)++; // 秒加1
if(*nSecond>=60) // 秒滿60,做出特殊處理,下面時,日,月等類同
{
*nSecond=0;
(*nMinute)++;
if(*nMinute>=60)
{
*nMinute=0;
(*nHour)++;
if(*nHour>=24)
{
*nHour=0;
(*nDate)++;
switch(*nMonth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
nDays=31;
break;
case 2:// 判斷閏年
if(*nYear%400==0||*nYear%100!=0&&*nYear%4==0)
{
nDays=29;
}
else
{
nDays=28;
}
break;
default:
nDays=30;
break;
}
if(*nDate>nDays)
{
*nDate=1;
(*nMonth)++;
if(*nMonth>12)
{
*nMonth=1;
(*nYear)++;
}
}
}
}
}
}
void main()
{
int nYear=2004,nMonth=12,nDate=31,nHour=59,nMinute=59,nSecond=59;
NextMinute(&nYear,&nMonth,&nDate,&nHour,&nMinute,&nSecond);
printf("The result:%d-%d-%d %d:%d:%d",nYear,nMonth,nDate,nHour,nMinute,nSeco
nd);
}