指定字符串的字符数组 [英] Assigning strings to arrays of characters

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

问题描述

我用下面有点意外。

实施例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 };

但它不允许你做assignmend因为s是一个阵列,而不是一个自由指针。的意义

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

s = "abcd"

是ABCD的指针值分配给的',但你不能改变•从那以后什么都不会指向数组。

这能够而且确实工作,如果s是一个的char * - 一个指针,能够指向任何

is to assign the pointer value of "abcd" to 's' but you can't change s since then nothing will point 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天全站免登陆