[英]Setting a value to a function in C
我正在嘗試在C語言中做一個反向String問題,我知道還有其他方法可以做到這一點,但是我對以下解決方案為什么不起作用感到困惑。 (我將輸出放在下面)
/*Write a function reverse (s) that reverses the character strings. Use it to write a program that reverses its input a line at a time*/
#include <stdio.h>
#define MAXLENGTH 1000
int ngetline(char s[], int lim);
void nreverse(char s[], int index);
main(){
int len;
char line[MAXLENGTH];
while(len = ngetline(line, MAXLENGTH) > 0)
{
printf("length: %d\n", len);
nreverse(line, len);
}
printf("%s", line);
return 0;
}
int ngetline(char s[], int lim)
{
int c;
int i;
for(i = 0; i < lim -1 && (c = getchar()) != EOF && c != '\n'; ++i)
{
s[i] = c;
}
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
printf("i: %d\n", i);
return i;
}
void nreverse(char s[], int len)
{
int i, backIndex;
int halfway;
char temp;
backIndex = len - 2;
halfway = backIndex / 2;
for(i = 0; i <= halfway; ++i)
{
printf("In the for\n");
temp = s[i];
s[i] = s[backIndex];
s[backIndex] = temp;
--backIndex;
}
}
這是輸出:
./reverseString
entering while
String to be Reversed
i: 22
length: 1
如您在代碼中所見,我將長度設置為等於返回i的函數ngetline()。 但是,當我打印/嘗試獲取長度時,它返回1。有人知道為什么會這樣嗎? 謝謝。
這是c
運算符的優先級 。 由於關系( >
)的優先級高於賦值( =
),因此它首先被求值,因此您將值True
(或1
)賦給變量len
。 嘗試將作業放在括號中:
while((len = ngetline(line, MAXLENGTH)) > 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.