将字符串分配给字符数组 [英] Assigning strings to arrays of characters

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

问题描述

我对以下内容感到有些惊讶.

I am a little surprised by the following.

示例 1:

char s[100] = "abcd"; // declare and initialize - WORKS

示例 2:

char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)

我想知道为什么第二种方法不起作用.它应该(它适用于其他数据类型)似乎很自然?有人能解释一下这背后的逻辑吗?

I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?

推荐答案

在初始化数组时,C 允许您用值填充它.所以

When initializing an array, C allows you to fill it with values. So

char s[100] = "abcd";

int s[3] = { 1, 2, 3 };

但它不允许您进行分配,因为 s 是一个数组而不是一个自由指针.

but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

s = "abcd" 

是将 abcd 的指针值分配给 s 但你不能改变 s 因为这样就没有任何东西指向数组了.
如果 s 是一个 char* - 一个可以指向任何东西的指针,这可以而且确实有效.

is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.

如果您想简单地复制字符串,请使用 strcpy.

If you want to copy the string simple use strcpy.

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

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