字符串在C字面 [英] string literal in c

查看:97
本文介绍了字符串在C字面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下code非法的?

Why is the following code illegal?

typedef struct{
   char a[6];
} point;

int main()
{
   point p;
   p.a = "onetwo";
}

它有什么用文字的大小?或者是它的后声明只是非法分配一个字符串到字符数组?

Does it have anything to do with the size of the literal? or is it just illegal to assign a string literal to a char array after it's declared?

推荐答案

它没有任何关系的大小。它的创建后,您不能分配一个字符串到字符数组 - 你只能在定义时使用它

It doesn't have anything to do with the size. You cannot assign a string literal to a char array after its been created - you can use it only at the time of definition.

当你做

char a[] = "something";

它创造足够的大小(包括终止空)的数组,并复制字符串数组。它不是来指定在一个字符串初始化数组的大小一个很好的做法 - 你可能不占空字符

it creates an array of enough size (including the terminating null) and copies the string to the array. It is not a good practice to specify the array size when you initialize it with a string literal - you might not account for the null character.

当你做

char a[10];
a = "something";

你想分配给数组的地址,这是违法的。

you're trying to assign to the address of the array, which is illegal.

编辑:在其他的答案提到的,你可以做的strcpy /函数strncpy,但要确保该阵列与所需要的长度初始化

as mentioned in other answers, you can do a strcpy/strncpy, but make sure that the array is initialized with the required length.

strcpy(p.a, "12345");//give space for the \0

这篇关于字符串在C字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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