【问题标题】:Please tell me what I am doing wrong because the value returned by monthstr2num is wrong [closed]请告诉我我做错了什么,因为monthstr2num返回的值是错误的[关闭]
【发布时间】:2012-09-28 18:50:01
【问题描述】:

请告诉我我做错了什么

//I'm trying to get the number of the month by sending its name.
#include <stdio.h>

我的功能

int monthstr2num (char month[]){                                                


if (month == "September")
    return 8;


}

int main (){
char month []={"September"};
int num;

num = monthstr2num (month);//func call

显示错误的输出,例如 37814040

printf ("%d", num);

return 0;
}

【问题讨论】:

  • 您是否尝试在启用所有警告的情况下编译您的代码(例如,使用 gcc -Wall -g mehdi.c -o mehdi-prog ?如果您这样做了,您应该会收到警告...

标签: c arrays string function


【解决方案1】:

你的问题出在两个地方。

首先是您使用== 比较字符串的地方,这在C 中是不可能的(这是未定义的行为,它可以编译但不会执行您想要的操作)。您必须使用 C 库中名为 strcmp 的函数。它位于string.h,可以这样使用:

if(strcmp(month,"September")==0)
    return 8;

另外,当那个 if 语句返回 false 时,你必须在 if 语句之外有另一个 return,例如 return 0;

【讨论】:

    【解决方案2】:

    这段代码有2个问题:

    1) (month == "September") 比较指针而不是实际数据

    2)当(month == "September")为false时,函数返回一些垃圾,因为这种情况没有return语句

    【讨论】:

      【解决方案3】:
      if (month == "September")
      

      错了。使用strcmp。我对这个编译有点惊讶(因为我的数组/指针细节并不完美),但这最终会将这两个实体的内存地址作为指针进行比较。

      【讨论】:

        【解决方案4】:

        不要使用== 来比较字符串。 C字符串是char *==会比较指针。

        C 标准库提供了用于比较 C 字符串的函数,例如:strcmp,只是 #include &lt;string.h&gt;

        【讨论】:

        • 从技术上讲,您可以在带有字符串文字的char* 值上使用==,但这是未定义的行为,启用所有警告的良好编译器应该会给您一个警告。但是代码会编译(具有未定义的行为)。
        猜你喜欢
        • 1970-01-01
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 2012-11-07
        • 2013-02-08
        相关资源
        最近更新 更多