[英]“initializer element is not constant char” error in 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);
如果要在代碼中初始化內存,則無需以這種方式分配內存,我的意思是:
#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數組,那么本主題應該啟發您: 使用malloc()為const 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);
}
除了main
內部,您還可以執行以下操作-
char *s="this is a string"; //string literal you can't modify it
要么
char s[]="this is a string"; // modifiable string
您將一個指向字符串常量的指針分配給變量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)騰出空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.