为什么一个字符串被分配到一个char *指针,而不是一个char []数组? [英] Why can a string be assigned to a char* pointer, but not to a char[] array?

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

问题描述

有人可以解释为什么这工作的指针:

 的char * STR1;STR1 =Hello1;STR1 =新建字符串;//但是不是这
CHAR STR2 [] =你好;
STR2赛车=四;// 或这个
CHAR STR3 [];
STR3 =你好;
STR3 =你好;


解决方案

为什么它的工作原理与指针:结果
当你说的char * STR1 在C,你是在分配内存的指针。当你写 = STR1你好; ,你正在创建一个字符串字面内存,使指针指向它。当您创建另一个字符串新建字符串并将其分配给 STR1 ,你正在做的是改变地方指针指向。

为什么不能使用数组:结果
当你说字符STR2 [] =你好,你正在创建一个字符串文字,它的定义中把它的数组中为止。它是确定没有给出大小,数组计算,并附加了一个'\\ 0'它。而不调整其大小不能重新分配任何数组。这就是为什么 STR2 =四个一将不起作用。

STR3 的情况下,同样的情况。您还没有定义在定义数组的大小,因此它计算出它的大小为0,你不能没有调整大小的数组分配任何新的东西。

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";

解决方案

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.

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 '\0' to it. You cannot reassign anything to that array without resizing it. That is why str2 = "four" will not work.

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天全站免登陆