雖然通過練習3-5中的在C編程語言,我遇到了以下意外行爲。爲什麼變量在C程序中被突變?
#include <stdio.h>
#include <string.h>
// inspired by: http://www.eng.uerj.br/~fariasol/disciplinas/LABPROG/C_language/Kernighan_and_Ritchie/solved-exercises/solved-exercises.html/krx305.html
void reverse(char s[]) {
int c, i, j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void itob(int n, char s[], int b) {
static char digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i = 0,
sign;
if (b < 2 || b > 36) {
fprintf(stderr, "EX3_5: Cannot support base %d\n", b);
}
if ((sign = n) < 0) {
n = -n;
}
do {
s[i++] = digits[n % b];
} while (n /= b);
if (sign < 0) {
s[i++] = '-';
}
s[i] = '\0';
reverse(s);
}
int main() {
int base = 2,
input;
char buffer[5] = "0000";
input = 127;
itob(input, buffer, base);
printf("%d in base %d is %s\n", input, base, buffer);
// 127 in base 2 is 1111111
input = 128;
itob(input, buffer, base);
printf("%d in base %d is %s\n", input, base, buffer);
// 0 in base 2 is 10000000
// Why is input now 0?!
return 0;
}
爲什麼input
變量存在的值改變(只有當input
大於127
更大)?我是C新手,但這似乎很意外。據我所知,函數參數是按值傳遞的。
較大'buffer'不夠大。你有一個緩衝區溢出和未定義的行爲。 – user2357112
將數組函數參數調整爲指針參數。雖然指針是按值傳遞的,但它們可以用來訪問調用者的內存。 –
@ user2357112謝謝 - 就是這樣。如果您將評論添加爲答案,我很樂意接受。 – pdoherty926