【问题标题】:assign a string value to pointer将字符串值分配给指针
【发布时间】: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


    【解决方案1】:

    在 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

    【讨论】:

    • 只是一些建议:将第一行中的= 更改为==,并明确month == &month[0] 大部分情况。 使用 sizeof 或某些其他语言时并非如此功能。
    【解决方案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 可能已经足够好(并且可能更有效)。

    【讨论】:

      【解决方案3】:
      tempMonth = month
      

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

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

      【讨论】:

        【解决方案4】:
        #include "string.h" // or #include <cstring> if you're using C++
        
        char *tempMonth;
        tempMonth = malloc(strlen(month) + 1);
        strcpy(tempMonth, month);
        printf("%s", tempMonth);
        

        【讨论】:

        • 有人会说,如果你使用printfmalloc,那么你不可能使用C++ - 你被困在等待完全转换的炼狱中:-)
        • 真的。你仍然可以包含 C 库。你永远不知道;)
        【解决方案5】:
        tempmonth = malloc (strlen (month) + 1); // allocate space
        strcpy (tempMonth, month);               //copy array of chars
        

        记住:

        include <string.h>
        

        【讨论】:

        • 有一个缓冲区溢出等待发生。始终使用strncpy,并确保 tempMonth 指向正确分配的内存。
        • 我没有对你投反对票,但我认为你的分配应该是strlen(month)+1sizeof(tempmonth)指针的大小。
        • 已修复并已投票。您知道,如果您想更改答案,您不必必须保持原样(我认为您可以在任何代表级别编辑自己的帖子)。
        【解决方案6】:

        你可以这样做:

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

        并获得访问权限

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多