如何创建一个字符串C中的数组? [英] How do I create an array of strings in C?
问题描述
我想如果我用这个code创建的字符串在C数组:
I am trying to create an array of strings in C. If I use this code:
char (*a[2])[14];
a[0]="blah";
a[1]="hmm";
海湾合作委员会给了我警告:从分配不兼容的指针类型。什么是做到这一点的正确方法?
gcc gives me "warning: assignment from incompatible pointer type". What is the correct way to do this?
编辑:我很好奇,为什么这应该给出一个编译器警告,因为如果我这样做的printf(A [1]),则它正确打印哼
edit: I am curious why this should give a compiler warning since if I do printf(a[1]);, it correctly prints "hmm".
推荐答案
如果你不想改变字符串,那么你可以简单地做
If you don't want to change the strings, then you could simply do
const char *a[2];
a[0] = "blah";
a[1] = "hmm";
当你像这样做,你会分配两个指针数组为const char
。然后,这些指针将被设置为静态字符串的地址嗒嗒
和哼
。
When you do it like this you will allocate an array of two pointers to const char
. These pointers will then be set to the addresses of the static strings "blah"
and "hmm"
.
如果你想能够改变的实际字符串的内容时,你必须做一些像
If you do want to be able to change the actual string content, the you have to do something like
char a[2][14];
strcpy(a[0], "blah");
strcpy(a[1], "hmm");
这将拨出14 字符
s分别连续两个阵列,在此之后,静态字符串的内容将被复制到他们。
This will allocate two consecutive arrays of 14 char
s each, after which the content of the static strings will be copied into them.
这篇关于如何创建一个字符串C中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!