【问题标题】:"initializer element is not constant char" error in CC中的“初始化元素不是常量字符”错误
【发布时间】:2015-09-18 14:00:00
【问题描述】:

这是我的代码:

#include <stdio.h>
#include<stdlib.h>
char *s = (char *)malloc (40);
int main(void)
{
    s="this is a string";
    printf("%s",s);
}

我收到以下错误:

错误:初始化元素不是常量 char *s = (char *)malloc (40);

【问题讨论】:

  • 问题是?
  • 你的问题解决了吗,阿迪亚?

标签: c


【解决方案1】:

如果你想在代码中初始化它,你不需要以这种方式分配内存,我的意思是:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *s = "this is a string"; // char s[] = "this is a string";
    printf("%s",s);

    return 0;
}

在这种情况下就足够了。如果您真的想将const char 字符串分配给您的char 数组,这个主题应该会启发您:Dynamically allocating memory for const char string using malloc()

【讨论】:

    【解决方案2】:

    不能不这样做。

    你可以这样做 -

    #include <stdio.h>
    #include<stdlib.h>
    #include <string.h>
    char *s;                    // probably should avoid using global variables
    int main(void)
    {
          s=malloc(40);
          strcpy(s,"this is a string");
          printf("%s",s);
          free(s);
    }
    

    除了main 里面的这个你可以这样做 -

    char *s="this is a string";    //string literal you can't modify it
    

    或者

    char s[]="this is a string";    // modifiable string
    

    【讨论】:

      【解决方案3】:

      您将指向字符串常量的指针分配给变量s,该变量未声明为指向常量。这就是你想要的:

      #include <stdio.h>
      
      int main(void)
      {
         const char *s = "this is a string";
      
         printf("%s\n", s);
         return 0;
      }
      

      在 C 中,基本上有三种方式来声明“字符串”变量。

      字符串常量指针

      如果你需要一个不会改变的字符串的名字,你可以像这样声明和初始化它

      const char *s = "a string";
      

      字符数组

      如果你需要一个字符串变量并且你事先知道它需要多长时间,你可以像这样声明和初始化它

      char s[] = "a string";
      

      或喜欢

      char s[9];
      
      strcpy(s, "a string");
      

      字符序列指针

      如果事先不知道数组需要多大,可以在程序执行的时候分配空间:

      char *s;
      
      s = malloc(strlen(someString) + 1);
      if (s != NULL) {
         strcpy(s, someString);
      }
      

      “+1”是为空字符(\0)腾出空间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-10
        • 2020-06-29
        • 2020-03-27
        • 2012-06-04
        • 1970-01-01
        • 2014-05-25
        • 1970-01-01
        相关资源
        最近更新 更多