为什么这种C字符串分配是非法的? [英] Why is this C-string assignment illegal?

查看:40
本文介绍了为什么这种C字符串分配是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例1: char s [] [6] = {"Hello","world"}; 在这种情况下,将在静态存储器中分配一个静态数组,然后将元素从此处复制到该数组中.以及第2种情况.

CASE 1: char s[][6]={"Hello","world"}; in this case, a static array is allocated in read-only memory and from there the elements are copied to the array. and in case 2.

案例2: char * s ="hello world"; 会将其放置在只读存储器中.

CASE 2: char* s= "hello world"; will place it in read-only memory.

所以我的问题是为什么

char s[][6]={"Hello","world"};
s[1]="lucky"; //is illegal

因为如果要从只读存储器中复制元素,那么为什么此语句 s [1] ="lucky"; 不能从只读存储器中复制到数组,因为数组是也分配给此字符串文字,并从此处将元素复制到s [1].我读了很多答案,所有人都在说有什么区别,但是没人告诉为什么吗?请以我为初学者的身份进行解释.

because if elements are being copied from read-only memory then why this statement s[1]="lucky"; can't be copied from read-only memory to array because an array is also allocated for this string literal and from there, elements are copied to s[1]. I have read many answers, and all are telling what's the difference but no one tells why? please explain as I am a beginner.

推荐答案

s[1]="lucky"; //is illegal

因为数组名称不是可修改的左值.因此,它们无法显示在作业的左侧.

because array names are not a modifiable lvalue. As a result they can't appear on the left of the assignment.

初始化不是分配.正是在初始化期间,字符串文字不会衰减为指针,而是将文字的值复制到内存中,这使我们可以修改其内容.(您显示的第一个例子就是这样的例子.)

Initialization is not assignment. It is during that initialization, when string literals don't decay into pointers, and rather the value of the literal is copied into memory which allow us to modify the content of it. (The first one you showed is an example of this).

根据标准: 6.7.9.p14

可以通过字符串文字或UTF-8字符串文字来初始化字符类型的数组,并可选地将其括在大括号中.字符串文字的连续字节(如果有空间或数组大小未知,则包括终止空字符)将初始化数组的元素.

An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

如果需要复制字符串,则必须使用 strcpy memcpy 等.

If you need to copy strings then you will have to use strcpy,memcpy etc.

这篇关于为什么这种C字符串分配是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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