如何在 C 中创建字符串数组? [英] How do I create an array of strings in C?
问题描述
我正在尝试在 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 给了我警告:从不兼容的指针类型赋值".这样做的正确方法是什么?
gcc gives me "warning: assignment from incompatible pointer type". What is the correct way to do this?
我很好奇为什么这会给出编译器警告,因为如果我执行 printf(a[1]);
,它会正确打印hmm".
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
的指针的数组.然后将这些指针设置为静态字符串 "blah"
和 "hmm"
的地址.
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 个 char
数组,之后静态字符串的内容将被复制到其中.
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屋!