【问题标题】:Setting a value to a function in C在 C 中为函数设置值
【发布时间】:2018-04-25 22:28:36
【问题描述】:

我正在尝试在 C 中做一个反向字符串问题,我知道还有其他方法可以做到这一点,但我对为什么以下解决方案不起作用感到困惑。 (我会把输出放在下面)

/*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 string reverse


    【解决方案1】:

    这是 c operator precedence 的事情。由于关系 (&gt;) 比赋值 (=) 具有更高的优先级,因此首先计算它,因此您将值 True(或 1)分配给变量 len。尝试将作业放在括号中:

    while((len = ngetline(line, MAXLENGTH)) > 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2011-07-12
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多