char * arr []和char arr []有什么区别? [英] What is the difference between the char *arr[] and char arr[] ?
问题描述
What is the difference between the
char *arr[4] = {"C","C++","Java","VBA"};
和
and
char arr[4] = {"C","C++","Java","VBA"};
推荐答案
第一个是char指针数组。所以数组的每个成员都指向一个char指针(通常是一个字符串)。
The first is an array of char pointers. So every member of the array is pointing to a char pointer (which often is a string).
char *arr[4];
arr[0]= "Codeproject";
arr[1]="is";
arr[2]="very";
arr[3]='"cool";
另一个只是一系列字符。它只存储一个字符。
你可以这样使用它:
The other is only an array of chars. It only stores ONE char.
You can use it this way:
char arr[4];
arr[0]='C';
arr[1]='o';
arr[2]='o';
arr[3]='l';
导入是要明白指针只指向内存或者对象,但不分配它。在这个示例代码中,所谓的硬编码字符串提供了内存。
Import is to understand that a pointer is ONLY pointing to memory or an object, but not allocating it. In this sample code the so called "hard coded strings" provide the memory.
尝试编译此代码,您无需询问:
< br $> b $ b
Try to compile this code and you don't need to ask:
/* is OK, a two-dimentional array of char */
char *arr[4] = {"C","C++","Java","VBA"};
< br $>
/* error C2040: 'char [4]' differs in levels of indirection from 'char *[4]' */
char arr[4] = {"C","C++","Java","VBA"};
第二种情况的错误是数组是一维的,只能占用4个字符,如:
The error in the second case is that the array is one-dimentional and can take only 4 characters like:
char arr1[4] = "C";
char arr2[4] = "C++";
char arr3[4] = "Java";
char arr4[4] = "VBA";
根据您使用的编译器,其中一个将无法编译。
第二个版本:
Depending on the compiler you use, one of those won't compile.
The second version:
char arr[4] = {"C","C++","Java","VBA"};
声明 arr
成为四个字符的数组,然后尝试为它提供一组四个指向字符的值。
一些编译器会抱怨太多的初始化器,因为第一个指针单独提供所有数据。
第一个版本:
Declares arr
to be an array of four characters, and then tries to supply it with a set of four pointer-to-character values.
Some compilers will complain "Too many initializers" because the first pointer alone provides all the data.
The first version:
char *arr[4] = {"C","C++","Java","VBA"};
声明 arr
是一个包含四个指针到字符值的数组,并为四个指针分配空间(即堆栈上可能是32位系统上的4 * 4字节,或64位系统上的8 * 4字节)。
第二个版本只分配4个字节 - 每个字符一个 - 所以你不能用字符串加载它而不会引起内存问题。
Declares arr
to be an array of four pointer-to-character values, and allocates space for four pointers (i.e. probably either 4*4 bytes on a 32 bit system, or 8*4 bytes on a 64 bit system) on the stack.
The second version only ever allocates 4 bytes - one for each character - so you can't load it with "strings" without causing memory problems.
这篇关于char * arr []和char arr []有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!