下面是一個程序的功能:字符串連接到另一個沒有分配,這是爲什麼?
//read the specified file and check for the input ssn
int readfile(FILE *fptr, PERSON **rptr){
int v=0, i, j;
char n2[MAXS+1], b[1]=" ";
for(i=0; i<MAXR; i++){
j=i;
if(fscanf(fptr, "%c\n%d\n%19s %19s\n%d\n%19s\n%d\n%19s\n%19s\n%d\n%d\n%19s\n\n",
&rptr[j]->gender, &rptr[j]->ssn, rptr[j]->name, n2, &rptr[j]->age,
rptr[j]->job, &rptr[j]->income, rptr[j]->major, rptr[j]->minor,
&rptr[j]->height, &rptr[j]->weight, rptr[j]->religion)==EOF) {
i=MAXR;
}
strcat(rptr[j]->name, b);
//strcat(rptr[j]->name, n2);
if(&rptr[MAXR]->ssn==&rptr[j]->ssn)
v=j;
}
return v;
}
的註釋行就是這樣,因爲某些原因,陣列「B」包含字符串「N2」儘管一個明顯缺乏分配。這發生在第一次strcat調用之前,但在fscanf調用之後。
它確實達到了預期的目標,但是爲什麼n2連接到b的末尾,特別是當b僅爲1個數組元素保留空間時?
下面是變量定義的的fscanf呼叫後一個片段:
*rptr[j]->name = "Rob"
b = " Low"
n2= "Low"
b不是空終止......它只有一個字符的空間......空間......它可能有東西在裏面,因爲你溢出了一個緩衝區。 – forsvarir 2011-05-23 14:13:04