问题描述
只是想真正用C我的头一轮数组和指针和它们之间的差异和时遇到一些麻烦二维数组。
Just trying to really get my head round Arrays and Pointers in C and the differences between them and am having some trouble with 2d arrays.
对于正常的一维数组,这是我已经学会了:
For the normal 1D array this is what I have learned:
char arr[] = "String constant";
创建字符数组和变量改编
将随时重新present当它被初始化创建的内存。
creates an array of chars and the variable arr
will always represent the memory created when it was initialized.
char *arr = "String constant";
创建了一个字符指针是当前指向的字符数组字符串常量的第一个指数。该指针可以稍后别的地方。
creates a pointer to char which is currently pointing at the first index of the char array "String constant". The pointer could point somewhere else later.
char *point_arr[] = {
"one", "two","three", "four"
};
创建指针,然后指向字符数组的数组一,二等。
creates an array of pointers which then point to the char arrays "one, "two" etc.
如果我们可以同时使用:
If we can use both:
char *arr = "constant";
和
char arr[] = "constant";
那么为什么我不能用:
then why can't I use:
char **pointer_arr = {
"one", "two", "three", "four"
};
而不是
char *pointer_arr[] = {
"one", "two", "three", "four"
};
如果我尝试的char **
东西然后我得到像标量初始化多余的元素错误。我可以通过使用专门分配内存释放calloc
使的char **
例如工作,但我没得与的char * ARR =嗒嗒做到这一点;
。我不明白为什么它是必要的,所以我真的不明白之间的区别:
If I try the char **
thing then I get an error like "excess elements in scalar initializer". I can make the char**
example work by specifically allocating memory using calloc
, but as I didn't have to do this with char *arr = "blah";
. I don't see why it is necessary and so I don't really understand the difference between:
char **arr_pointer;
和
char *arr_pointer[];
在事先非常感谢你的建议。
Many thanks in advance for your advice.
推荐答案
在总之,你不能使用 {...}
作为一个标量的初始化器。
In short, you cannot use { ... }
as an initialiser for a scalar.
的char ** arr_pointer
声明了一个标量,而不是一个数组。相比之下,原因你可以做的char * ARR =恒;
是因为你还在声明标量,它只是发生在一个字符串字面点
char **arr_pointer
declares a scalar, not an array. In contrast, the reason you can do char *arr = "constant";
is because you're still declaring a scalar, it just happens to point at a string literal.
这篇关于二维数组和指针 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!