如何在C语言中创建字符串数组?

11
我是一名有用的助手,可以为您翻译文本。
我正在从一本书中自学C语言,并尝试创建一个填字游戏。我需要创建一个字符串数组,但总是遇到问题。另外,我对数组不是很了解...
这是代码片段:
char word1 [6] ="fluffy", word2[5]="small",word3[5]="bunny";

char words_array[3]; /*This is my array*/

char *first_slot = &words_array[0]; /*I've made a pointer to the first slot of words*/

words_array[0]=word1; /*(line 20)Trying to put the word 'fluffy' into the fist slot of the array*/ 

但我不断收到这个消息:
crossword.c:20:16: warning: assignment makes integer from pointer without a cast [enabled by default]

不确定问题出在哪里...我尝试查找如何创建字符串数组的方法,但没有成功。

任何帮助将不胜感激,

Sam


尝试多学习一些关于数组的知识,可以参考这个网址:http://pw1.netcom.com/~tjensen/ptr/pointers.htm。 - hopper
顺便提一下 - char word1 [6] ="fluffy" - "fluffy"实际上是7个字符。在C中,字符串以\0结尾 - 这占用了一个额外的字符。 - ArjunShankar
2
const char* arr[] = { "literal", "string", "pointer", "array"};,请注意 const - WhozCraig
&words[0] 嗯...在那个点上似乎没有变量 words。你是复制代码时出错了还是漏掉了什么? - dmckee --- ex-moderator kitten
@ArjunShankar 哦,是的,我忘记了\0,谢谢。 - Wobblester
显示剩余2条评论
4个回答

17
words_array[0]=word1;

word_array[0]是一个char,而word1是一个char *。你的字符无法保存地址。

字符串数组可能看起来像这样:

char array[NUMBER_STRINGS][STRING_MAX_SIZE];

如果您更喜欢使用指向字符串的指针数组:
char *array[NUMBER_STRINGS];

然后:

array[0] = word1;
array[1] = word2;
array[2] = word3;

也许你应该阅读this

10
If you need an array of strings. There are two ways:
1. Two Dimensional Array of characters
In this case, you will have to know the size of your strings beforehand. It looks like below:
// This is an array for storing 10 strings,
// each of length up to 49 characters (excluding the null terminator).
char arr[10][50]; 

2. 字符指针数组

它的形式如下:

// In this case you have an array of 10 character pointers 
// and you will have to allocate memory dynamically for each string.
char *arr[10];

// This allocates a memory for 50 characters.
// You'll need to allocate memory for each element of the array.
arr[1] = malloc(50 *sizeof(char));

9

The declaration

char words_array[3];

创建一个由三个字符组成的数组。您似乎想要声明一个字符指针的数组:

char *words_array[3];

你有一个更严重的问题。这个声明
char word1 [6] ="fluffy";

创建了一个六个字符的数组,但实际上你告诉它拥有七个字符。所有字符串都有一个额外的字符'\0',用于表示字符串的结尾。
要么声明该数组大小为七:
char word1 [7] ="fluffy";

或者不指定尺寸,编译器会自动计算大小。
char word1 [] ="fluffy";

6

你也可以使用malloc()手动分配内存:

int N = 3;
char **array = (char**) malloc((N+1)*sizeof(char*));
array[0] = "fluffy";
array[1] = "small";
array[2] = "bunny";
array[3] = 0;

如果你在编写代码时不知道数组中会有多少个字符串,以及它们的长度,那么这是一种解决方法。但是当不再使用内存时,你需要释放它们(调用free()函数)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接