为什么可以将字符串分配给 char* 指针,但不能分配给 char[] 数组? [英] Why can a string be assigned to a char* pointer, but not to a char[] array?

查看:27
本文介绍了为什么可以将字符串分配给 char* 指针,但不能分配给 char[] 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下为什么这适用于指针吗:

Can someone explain why this works with the pointer:

char * str1;

str1 = "Hello1";

str1 = "new string";

// but not this
char str2 [] = "hello";
str2 = "four";

// or this
char str3 [];
str3 = "hello";
str3 = "hello";

推荐答案

为什么使用指针:
当你在 C 中说 char * str1 时,你是在内存中分配一个指针.当您编写 str1 = "Hello"; 时,您正在内存中创建一个字符串文字并让指针指向它.当您创建另一个字符串文字 "new string" 并将其分配给 str1 时,您所做的只是更改指针指向的位置.

Why it works with pointers:
When you say char * str1 in C, you are allocating a pointer in the memory. When you write str1 = "Hello";, you are creating a string literal in memory and making the pointer point to it. When you create another string literal "new string" and assign it to str1, all you are doing is changing where the pointer points.

为什么它不适用于数组:
当您说 char str2 [] = "Hello" 时,您正在创建一个字符串文字并在其定义期间将其放入数组中.可以不给出大小,因为数组会计算它并附加一个 '' 到它.您不能在不调整其大小的情况下将任何内容重新分配给该数组.这就是 str2 = "four" 不起作用的原因.

Why it doesn't work with arrays:
When you say char str2 [] = "Hello", you are creating a string literal and putting it in the array during its definition. It is ok to not give a size, as the array calculates it and appends a '' to it. You cannot reassign anything to that array without resizing it. That is why str2 = "four" will not work.

str3的情况相同.您还没有在定义中定义数组的大小,因此它计算出它的大小为 0.如果不调整数组大小,您将无法分配任何新内容.

In case of str3, it is the same case. You haven't defined the size of the array in the definition, so it calculated its size to be 0. You cannot assign anything new without resizing the array.

这篇关于为什么可以将字符串分配给 char* 指针,但不能分配给 char[] 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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