&引用;初始值设定项元素不是常量char“;C中的错误

&引用;初始值设定项元素不是常量char“;C中的错误,c,C,这是我的密码: #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); 内部主(空) { s=“这是一个字符串”; printf(“%s”,s); } 我得到以下错误: 错误:初始值设定项元素

这是我的密码:

#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);
内部主(空)
{
s=“这是一个字符串”;
printf(“%s”,s);
}
我得到以下错误:

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


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

#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;
}
#包括
#包括
内部主(空)
{
char*s=“这是一个字符串”;//char s[]=“这是一个字符串”;
printf(“%s”,s);
返回0;
}

在这种情况下就足够了。如果您真的想将
const char
字符串分配给您的char数组,本主题应该会启发您:

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

#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;
}
#包括
#包括
内部主(空)
{
char*s=“这是一个字符串”;//char s[]=“这是一个字符串”;
printf(“%s”,s);
返回0;
}
在这种情况下就足够了。如果您确实想将
常量char
字符串分配给您的char数组,本主题应该会告诉您:

您不能这样做

你可以这样做-

#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);
}

你不能那样做

你可以这样做-

#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);
}


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

#include <stdio.h>

int main(void)
{
   const char *s = "this is a string";

   printf("%s\n", s);
   return 0;
}
字符数组 如果您需要一个字符串变量,并且预先知道它需要多长时间,您可以像这样声明和初始化它

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)腾出空间。

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

#include <stdio.h>

int main(void)
{
   const char *s = "this is a string";

   printf("%s\n", s);
   return 0;
}
字符数组 如果您需要一个字符串变量,并且预先知道它需要多长时间,您可以像这样声明和初始化它

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)腾出空间。

问题是?你的问题解决了吗,Aditya?问题是?你的问题解决了吗,Aditya?