将字符串分配给char数组 [英] Assigning a string of characters to a char array

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

问题描述

我想知道为什么第一个语句工作,为什么不是第二个在c ++中

I Want to know why the first statements works and why not second one in c++

char a[10]="iqbal";  // it works

a="iqbal"; // does not work 


推荐答案

严格地说,不是指针! 和数组(数组的基址)不能是可修改的左值 。即它不能出现在赋值运算符的左侧。仅在某些情况下,数组衰减为指针。请阅读此 SO post 以了解阵列何时衰减为指针。这里还有一个好文章,解释了数组和指针之间的区别

Strictly speaking, an array is not a pointer! And an array ( base address of the array ) cant be a modifiable lvalue. ie it cannot appear on the left hand side of an assignment operator.Arrays decay into pointers only in certain circumstances. Read this SO post to learn when arrays decay into pointers. Here is one more nice article which explains the differences between arrays and pointers

另请参阅左值和右值这里,以便您了解不能出现在 = 的LHS上的事情。

Also read about lvalues and rvalues here so that you get an idea of things which cannot appear on the LHS of =


char a [10] =iqbal // it works

char a[10]="iqbal";  // it works

在这种情况下,内部会发生什么

In this case, internally what happens is

a[0] = 'i';
a[1] = 'q'; 
 .
 .
a[5] = '\0';

所以一切都很好,因为 array [i] 是可修改的左值。

So everything is fine as array[i] is a modifiable lvalue.


a =iqbal //不起作用

a="iqbal"; // does not work

在内部,这大致相当于

0x60000(Address of a, but is a simple number here ) = Address of "iqbal"

这是错误的,因为我们不能给一个数字赋值。

This is wrong as we cannot assign something to a number.

这篇关于将字符串分配给char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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