c - C 中的 "initializer element is not constant char"错误

标签 c

这是我的代码:

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

我收到以下错误:

error: initializer element is not constant 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 数组,这个主题应该会给你启发:Dynamically allocating memory for const char string using malloc()

关于c - C 中的 "initializer element is not constant char"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653942/

相关文章:

c++ - 在 C++ 中使用 Rust 库时 undefined reference

c - 打印二维数组内容的不同方式

c - 如何从文本文件 (C) 中读取特定数据?

c - 字符串格式、strtok 问题

c - ENXIO 对于 i2c ioctl 意味着什么?

c++ - 如何在 C++ winapi 中获取加载图标的大小

android - Android应用程序是否可以与C语言中的非Android应用程序共享UID

c - MPI 发送数组数组

c - 如何计算除双引号或单引号之外的字符?

c - 如何在C中查找2xn维数组中元素的频率