char *和int * [英] The difference between char* and int*
问题描述
char *
和 int *
之间有什么区别?当然,他们是不同的类型,但我怎么能写
char * s1 =hello world
为
hello world
它不是一个字符,我不能写
* s1
作为
char * s1 = {'h','e' ,'l','o','','w','o','r','l','d'
和
int * a = {2,3,1,45,6};
有什么区别?
很简单:一个字符串文字,即foobar
被编译为一个字符数组, (即,所有常量都存储在其中)和空终止。然后,将这个赋给一个变量只是为这个变量分配一个指向这个内存的指针。例如, const char * a =foo;
将分配foo
c $ c> a 。
简单来说,一个字符串常量已经带来了内存的存储空间。
相反,使用初始化器列表初始化指针(即大括号内的元素列表)不会为指针定义。非正式地,与字符串字面相反的初始化器列表的问题是它不带自己的内存。因此,我们必须提供初始化器列表可以存储其字符的内存。这是通过声明一个数组而不是一个指针。这编译得很好:
char s1 [11] = {'h','e','l','l' ,'o','','w','o','r','l','d'}
现在,通过声明 s1
作为数组,我们提供了存储字符的空间。
注意,你可以使用指针的大括号初始化,例如:
char * c2 = {nullptr} ;但是,虽然语法看起来是相等的,但这个东西完全不同,这就是所谓的统一初始化,只是简单的初始化。 c2
与 nullptr
。
What is the difference between char*
and int*
? Sure, they are of different types, but how is it that I can write
char* s1="hello world";
as
"hello world"
it is not a one character, it's an array of characters, and I cannot write
*s1
as
char* s1 = {'h','e','l','l','o',' ','w','o','r','l','d'};
and
int* a = {2,3,1,45,6};
What is the difference?
解决方案 It is quite simple: A string literal, i.e., "foobar"
is compiled to an array of chars which is stored in the static section of your program (i.e., where all constants are stored) and null terminated. Then, assigning this to a variable simply assigns a pointer to this memory to the variable. E.g., const char* a = "foo";
will assign the address where "foo"
is stored to a
.
In short, a string constant already brings the memory where it is to be stored with it.
In contrast, initializing a pointer with an initializer list, (i.e., a list of elements inside curly braces) is not defined for pointers. Informally, the problem with an initializer list -- in contrast to a string literal -- is that it does not "bring its own memory". Therefore, we must provide memory where the initializer list can store its chars. This is done by declaring an array instead of a pointer. This compiles fine:
char s1[11]={'h','e','l','l','o',' ','w','o','r','l','d'}
Now, we provided the space where the chars are to be stored by declaring s1
as an array.
Note that you can use brace initialization of pointers, though, e.g.:
char* c2 = {nullptr};
However, while the syntax seems equal, this something completely different which is called uniform initialization and will simply initialize c2
with nullptr
.
这篇关于char *和int *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!