为字符指定一个字符串值

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

如何为tempMonth分配月份? 谢谢

以及如何打印出来?

谢谢

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

所以你可以这样做:

 tempMonth=month; 

这将指向未分配的指针tempMonth指向在post的其他5行中分配的文字字节。

要创建字符串文字,执行此操作也更简单:

 char month[]="jan"; 

或者(虽然你不允许修改这个中的字符):

 char *month="jan"; 

编译器将使用正确的NULL终止的C字符串自动分配month[]右侧的文字长度, month将指向文字。

要打印它:

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

您可能希望查看C字符串和C字符串文字 。

 tempMonth = month 

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

如果你想要的是一个副本 – 你需要分配内存(使用malloc )然后实际复制值(如果它是一个以null结尾的字符串,则使用strcpy ,否则为memcpy或循环)。

如果您只想要指针的副本可以使用:

 tempmonth = month; 

但这意味着两者都指向相同的基础数据 – 更改一个并且它会影响两者。

如果你想要独立的字符串,你的系统很可能会有strdup ,在这种情况下你可以使用:

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

如果您的实现没有 strdup ,请获取一个 :

 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可能足够好(并且可能更有效)。

 #include "string.h" // or #include  if you're using C++ char *tempMonth; tempMonth = malloc(strlen(month) + 1); strcpy(tempMonth, month); printf("%s", tempMonth); 
 tempmonth = malloc (strlen (month) + 1); // allocate space strcpy (tempMonth, month); //copy array of chars 

记得:

 include  

你可以这样做:

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

并获得访问权限

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