【发布时间】:2021-10-29 09:16:56
【问题描述】:
明显的新手问题,我正在尝试写一些你放在 int 中的东西,它会给你一个月。这是一个函数python版本:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def get_month(mon):
return months[mon]
在 C 中,我已经这样做了:
#include <stdio.h>
char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int main()
{
char get_month(int m)
{
return *months[m];
}
for (int i = 0; i < 12; i++)
{
char this_month = get_month(i);
printf ("Month %d is %c\n", i, this_month);
}
return 0;
}
我得到这个输出
Month 1 is J
Month 2 is F
Month 3 is M
Month 4 is A
Month 5 is M
Month 6 is J
Month 7 is J
Month 8 is A
Month 9 is S
Month 10 is O
Month 11 is N
Month 12 is D
我认为我必须以某种方式考虑 *months[12] 中字符串的长度(或者它们在技术上是字符吗?),但我不知道如何。如果我将其更改为 *months[12][3] 我会得到
warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]
另外,如果它们的长度不一样(即月份被完全写出来)怎么办?
【问题讨论】:
-
所以你想得到整个月?
-
考虑一下:
get_month返回一个char,但您希望它返回一个字符串,即指向字符数组char *的指针,那么解决方案应该很明显。
标签: arrays c char c-strings function-definition