<C语言知识点 —— 数组赋值字符串>

1.定义的时候直接用字符串赋值

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


char a[10]="hello";
注意:不能先定义再给它赋值,这样是错误的!a虽然是指针,但是它已经指向在堆栈中分配的10个字符空间,现在这个情况a又指向数据区中的hello常量,这里的指针a出现混乱,不允许!
正确的做法是在声明中直接定义字符数组或者使用strcpy函数。
char a[10];
strcpy(a, "hello");使用字符串复制函数strcpy

char a[10]={'h','e','l','l','o'};逐个赋值;
char a[10]="hello";声明中直接定义;
#include <stdio.h>
main()
{
    char s[10];
    char r[10]="1 2 3 4 5";//在声明中可以对字符数组进行定义,但此处的=并不是赋值运算符。//
    strcpy(s,r);
    printf("s是:%s
",s);

}
原文地址:https://www.cnblogs.com/zhuangquan/p/14381919.html