在以下代碼中,char陣列在位置1和位置2處最多打印100個字符,但在位置3處僅打印22.此行爲的原因是什麼?char陣列本身(K&R1-16&1-17)
#include<stdio.h>
/* print the longest input line */
/*Exercise 1-16. Revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text.*/
#define MAXLENGTH 100
int mygetline(char s[], int limit);
void charcopy(char to[], char from[]);
int main(){
char current[MAXLENGTH];
char longest[MAXLENGTH];
int curlen;
int maxlen;
maxlen = 0;
while((curlen = mygetline(current, MAXLENGTH)) > 0){
if (curlen > 80)
printf("\nvery long:%d; %s\n", curlen, current);//#1# prints 100 digits
if(curlen>maxlen){
maxlen=curlen;
charcopy(longest, current);
printf("\nlonger:%d; %s\n", maxlen, longest);//#2# prints 100 digits
}
}
if (maxlen)//char array seems to truncates itself at scope boundry.
printf("\nlongest:%d; %s\n", maxlen, longest);//#3# prints 22 digits
printf("\nall done!\n");
return 0;
}
int mygetline(char s[], int limit){
int i, c;
for(i=0; i < limit-1 && ((c=getchar()) != EOF) && c != '\n'; ++i)
s[i]=c;
if(c=='\n'){
s[i]=c;
++i;}
else
if(i >= limit-1)
while (((c=getchar()) != EOF) && c != '\n')
++i;
s[i]='\0';
return i-1;
}
void charcopy(char to[], char from[]){
int i;
i=0;
while((to[i] = from[i]) != '\0'){
++i;}
}
它的位置標記爲3註釋中只打印22個字符而不是100個。它非常奇怪。
編輯: 作爲每斯科茨答案,我已經改變mygetline這樣:
int mygetline(char s[], int limit){
int i, c, k;
for(i=0; i < limit-1 && ((c=getchar()) != EOF) && c != '\n'; ++i)
s[i]=c;
if((c=='\n') && (i < limit -1)){
s[i]=c;
++i;}
else{//if we are over the limit, just store the num of char entered without storing chars
k = 0;
while (((c=getchar()) != EOF) && c != '\n')
++k;}
s[i]='\0';
return i+k;
}
如可以看到的,如果輸入過沖限制,然後NUM輸入的字符被存儲在完全新的變量,K這不接觸陣列。我仍然截斷了最後一行打印的行,並且我得到奇怪的32770作爲行長度。爲什麼?可以看出,陣列正在被嬰兒坐着,蹣跚學步,並且只餵食精確量的焦炭而不再飲食。
編輯:第一個列表的問題是,正如斯科特所指出的那樣,我是超數組。第二個mygetline的問題是k=0;
在if嵌套中初始化。向上移動初始化並使其成爲全局函數,似乎解決了第二個問題。
工作mygetline如下:
int mygetline(char s[], int limit){
int i, c, k;
k=0;
for(i=0; i < limit-1 && ((c=getchar()) != EOF) && c != '\n'; ++i)
s[i]=c;
if((c=='\n') && (i < limit -1)){
s[i]=c;
++i;}
else{//if we are over the limit, just add the num of char entered without storing chars
while (((c=getchar()) != EOF) && c != '\n')
++k;}
s[i]='\0';
return i+k;
}
認識到,除非我們知道'mygetline'和'charcopy'做了什麼,否則我們不能回答這個問題,第三行打印maxlen = 100或者maxlen = 22? –
試圖這樣做。我可以看到...... – aamermoquim
你的問題出現在mygetline中,你是否看到了一種可以寫在數組邊界之外的方式?這會破壞你的數據(你可以相當安全地打賭它不在代碼中)原本是K&R的...... :-)事實上,直接導致問題的線路是他們的,但你改變了它的表現他們有。) –