在 C 中,为什么我不能在声明后将字符串分配给 char 数组? [英] In C, why can't I assign a string to a char array after it's declared?

查看:18
本文介绍了在 C 中,为什么我不能在声明后将字符串分配给 char 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这件事困扰了我一段时间.

This has been bugging me for a while.

struct person {
       char name[15];
       int age;
};
struct person me;
me.name = "nikol";

编译时出现此错误:

错误:从类型char *"分配给类型char[15]"时类型不兼容

error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’

我在这里遗漏了什么明显的东西吗?

am I missing something obvious here?

推荐答案

数组是C语言的二等公民,不支持赋值.

Arrays are second-class citizens in C, they do not support assignment.

char x[] = "This is initialization, not assignment, thus ok.";

这不起作用:

x = "Compilation-error here, tried to assign to an array.";

使用库函数或手动复制每个元素:

Use library-functions or manually copy every element for itself:

#include <string.h>
strcpy(x, "The library-solution to string-assignment.");

这篇关于在 C 中,为什么我不能在声明后将字符串分配给 char 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆