2011-04-18 162 views
5
char *tempMonth; 

char month[4]; 
month[0]='j'; 
month[1]='a'; 
month[2]='n'; 
month[3]='\0'; 

如何将月份指定给tempMonth?谢谢指定一个字符串值指针

以及如何最终打印出来?

感谢

回答

1
tempmonth = malloc (strlen (month) + 1); // allocate space 
strcpy (tempMonth, month);    //copy array of chars 

记住:

include <string.h> 
+0

有一个缓冲区溢出等待发生。始终使用'strncpy',并确保tempMonth指向正确分配的内存。 – 2011-04-18 03:58:41

+0

我没有降低你的评分,但我认为你的分配应该是'strlen(month)+ 1'。 'sizeof(tempmonth)'是_pointer._ – paxdiablo 2011-04-18 03:59:15

+0

的大小哦。你是对的。对不起 – Freaktor 2011-04-18 04:00:14

10

在C中,month == &month[0](大多数情况下),并且这些等于char *或字符指针。

所以,你可以这样做:

tempMonth=month; 

这将指向未分配的指针tempMonth指向在其他5条线路的职位分配的字面字节。

要使一个字符串,它也是这样更简单:

char month[]="jan"; 

或者(虽然你是不允许修改在这一个字符):

char *month="jan"; 

的编译器会自动分配month[]右侧文字的长度,并使用适当的以NULL结尾的C字符串,并且month将指向文字。

要打印:

printf("That string by golly is: %s\n", tempMonth); 

您不妨审查C strings and C string literals

+0

只是一些建议:在第一行中将'='改为'==',并明确说明'month ==&month [0]'_mostly._使用sizeof或某些其他语言功能时不会这样。 – paxdiablo 2011-04-18 04:09:08

+0

是的,同意...... – 2011-04-18 04:11:51

+0

@paxdiablo:是的,很好的编辑。谢谢。 – 2011-04-18 04:20:55

2
tempMonth = month 

当你给一个指针赋值时 - 它是一个指针,而不是一个字符串。通过如上分配,您不会奇迹般地拥有相同字符串的两个副本,您将有两个指针(monthtempMonth)指向相同的字符串。

如果你想要的是一个副本 - 你需要分配内存(使用malloc),然后实际复制值(使用strcpy如果它是一个空终止字符串,memcpy或循环其他)。

0

你可以这样做:

char *months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep","Oct", "Nov", "Dec"}; 

并访问

printf("%s\n", months[0]); 
2

如果你只想指针的一个拷贝,可以使用:

tempmonth = month; 

但这意味着两者都指向相同的基础数据 - 更改一个并影响博日。

如果你想独立的字符串,有一个很好的机会,你的系统将具有strdup,在这种情况下,你可以使用:

tempmonth = strdup (month); 
// Check that tempmonth != NULL. 

如果您的实施strdupget one

char *strdup (const char *s) { 
    char *d = malloc (strlen (s) + 1); // Allocate memory 
    if (d != NULL) strcpy (d,s);   // Copy string if okay 
    return d;       // Return new memory 
} 

为了以格式化的方式打印字符串,请查看printf家族,尽管对于像这样的简单字符串转换为标准输出,puts可能已经足够好了(可能更有效率)。

1
#include "string.h" // or #include <cstring> if you're using C++ 

char *tempMonth; 
tempMonth = malloc(strlen(month) + 1); 
strcpy(tempMonth, month); 
printf("%s", tempMonth); 
+0

有人会说,如果你使用'printf'或'malloc',那么你不可能使用C++ - 你被困在炼狱中等待完全转换:-) – paxdiablo 2011-04-18 04:11:02

+0

是真的。尽管如此,你仍然可以包含C库。你永远不会知道 ;) – 2011-04-18 04:34:17