【发布时间】:2011-04-18 03:53:09
【问题描述】:
char *tempMonth;
char month[4];
month[0]='j';
month[1]='a';
month[2]='n';
month[3]='\0';
如何将月份分配给 tempMonth?谢谢
最后如何打印出来?
谢谢
【问题讨论】:
标签: c
char *tempMonth;
char month[4];
month[0]='j';
month[1]='a';
month[2]='n';
month[3]='\0';
如何将月份分配给 tempMonth?谢谢
最后如何打印出来?
谢谢
【问题讨论】:
标签: c
在 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);
【讨论】:
= 更改为==,并明确month == &month[0] 大部分情况。 使用 sizeof 或某些其他语言时并非如此功能。
如果你只想要一个指针的副本,你可以使用:
tempmonth = month;
但这意味着两者都指向相同的基础数据 - 更改一个会影响两者。
如果你想要独立的字符串,你的系统很有可能会有strdup,在这种情况下你可以使用:
tempmonth = strdup (month);
// Check that tempmonth != NULL.
如果您的实现没有有strdup、get 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 可能已经足够好(并且可能更有效)。
【讨论】:
tempMonth = month
当你给一个指针赋值时——它是一个指针,而不是一个字符串。通过如上分配,您不会奇迹般地拥有相同字符串的两个副本,您将拥有两个指向 same 字符串的指针(month 和 tempMonth)。
如果你想要的是一个副本 - 你需要分配内存(使用malloc)然后实际复制值(如果它是一个空终止字符串,则使用strcpy,memcpy 或循环否则)。
【讨论】:
#include "string.h" // or #include <cstring> if you're using C++
char *tempMonth;
tempMonth = malloc(strlen(month) + 1);
strcpy(tempMonth, month);
printf("%s", tempMonth);
【讨论】:
printf 或malloc,那么你不可能使用C++ - 你被困在等待完全转换的炼狱中:-)
tempmonth = malloc (strlen (month) + 1); // allocate space
strcpy (tempMonth, month); //copy array of chars
记住:
include <string.h>
【讨论】:
strncpy,并确保 tempMonth 指向正确分配的内存。
strlen(month)+1。 sizeof(tempmonth) 是指针的大小。
你可以这样做:
char *months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep","Oct", "Nov", "Dec"};
并获得访问权限
printf("%s\n", months[0]);
【讨论】: