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

时间:2013-03-01 15:59:40

标签: c arrays string

我正在从一本书中自学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]

不确定是什么问题...我试图查找如何制作字符串数组但没有运气

非常感谢任何帮助,

萨姆

4 个答案:

答案 0 :(得分:14)

words_array[0]=word1;

word_array[0]char,而word1char *。你的角色无法持有地址。

字符串数组可能如下所示:

char array[NUMBER_STRINGS][STRING_MAX_SIZE];

如果您想要一个指向字符串的指针数组:

char *array[NUMBER_STRINGS];

然后:

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

也许你应该阅读this

答案 1 :(得分:7)

声明

char words_array[3];

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

char *words_array[3];

但是你有一个更严重的问题。声明

char word1 [6] ="fluffy";

创建一个包含六个字符的数组,但实际上它告诉它有七个字符。所有字符串都有一个额外的字符'\0',用于表示字符串的结尾。

将数组声明为7:

char word1 [7] ="fluffy";

或保留大小,编译器将自行解决:

char word1 [] ="fluffy";

答案 2 :(得分:6)

如果您需要一个字符串数组。有两种方法:

<强> 1。二维字符数组

在这种情况下,您必须事先知道字符串的大小。它看起来如下:

// 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));

答案 3 :(得分:4)

您也可以使用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())。

相关问题