2012-09-28 43 views
-3

请告诉我,我做错了请告诉我,我做错了,因为monthstr2num返回的值是错误

//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; 
} 
+0

你尝试编译代码并启用所有的警告(例如''gcc -Wall -g mehdi.c -o mehdi-prog'?如果你这样做,你应该会得到警告...... –

回答

3

你的问题在于两个地方。

首先是你在哪里使用==来比较一个字符串,这在C中是不可能的(这是未定义的行为,它编译但不会做你想做的)。您必须在名为strcmp的C库中使用一个函数。它位于string.h,可以像这样使用:

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

此外,当if语句返回false,你必须有if语句之外的另一个回报,比如return 0;

0
if (month == "September") 

错误。使用strcmp。我对这个编译有点惊讶(因为我在数组/指针微妙方面并不完美),但是这会将这两个实体的内存地址作为指针进行比较。

0

请勿使用==来比较字符串。 C字符串是char *,而==将比较指针。

C标准库提供比较C字符串的函数,例如:strcmp,只是#include <string.h>

+0

技术上来说,你可以在'char *'值上使用'=='一个字符串文字,但它是未定义的行为,并且一个启用了所有警告的好编译器应该给你一个警告,但是代码会编译(具有未定义的行为)。 –

1

这段代码有2个问题:

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

2)当(month == "September")是假的,该函数返回一些垃圾,因为那里是没有return语句这种情况下

相关问题