将一个字符数组分配给另一个字符数组将给出错误.为什么? [英] Assigning one character array to another gives Error. Why?

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

问题描述

数组的名称是指向第一个元素的指针.那么为什么一个字符数组不能分配给另一个数组呢?

Name of an array is pointer to the first element. So Why one character array cannot be assigned another array ?

#include<stdio.h>
int main()
{
  char str1[]="Hello";
  char str2[10];
  char *s="Good Morning";
  char *q;
  str2=str1;  /* Error */
  q=s; /* Works */
  return 0;
}

推荐答案

表达式中的数组会自动转换为指向数组第一个元素的指针,但sizeof运算符和一元&运算符的操作数除外,因此您不能分配给数组.

Arrays in expressions automatically converted to pointer pointing to the first element of the array except for operands of sizeof operator and unary & operator, so you cannot assign to arrays.

在代码的开头添加#include <string.h>并使用strcpy()是复制字符串的好方法之一.

Adding #include <string.h> to the head of your code and using strcpy() is one of good ways to copy strings.

#include<stdio.h>
#include<string.h>
int main(void)
{
  char str1[]="Hello";
  char str2[10];
  char *s="Good Morning";
  char *q;
  strcpy(str2, str1);  /* Works */
  q=s; /* Works */
  return 0;
}

这篇关于将一个字符数组分配给另一个字符数组将给出错误.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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