Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c - 如何在C中创建字符串数组?(How do I create an array of strings in C?)

I am trying to create an array of strings in C. If I use this code:

(我试图在C中创建一个字符串数组。如果我使用此代码:)

char (*a[2])[14];
a[0]="blah";
a[1]="hmm";

gcc gives me "warning: assignment from incompatible pointer type".

(gcc给我“警告:从不兼容的指针类型分配”。)

What is the correct way to do this?

(这样做的正确方法是什么?)

edit: I am curious why this should give a compiler warning since if I do printf(a[1]);

(编辑:我很好奇为什么这应该给编译器警告,因为如果我做printf(a[1]);)

, it correctly prints "hmm".

(,它正确打印“嗯”。)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want to change the strings, then you could simply do

(如果您不想更改字符串,那么您可以这样做)

const char *a[2];
a[0] = "blah";
a[1] = "hmm";

When you do it like this you will allocate an array of two pointers to const char .

(当你这样做时,你将分配一个两个指向const char指针的数组。)

These pointers will then be set to the addresses of the static strings "blah" and "hmm" .

(然后将这些指针设置为静态字符串"blah""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");

This will allocate two consecutive arrays of 14 char s each, after which the content of the static strings will be copied into them.

(这将分配两个连续的14个char的数组,之后静态字符串的内容将被复制到它们中。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...