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

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

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

任何帮助都感激不尽,

山姆

 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; 

也许你应该读这个 。

声明

 char words_array[3]; 

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

 char *words_array[3]; 

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

 char word1 [6] ="fluffy"; 

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

声明数组的大小为7:

 char word1 [7] ="fluffy"; 

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

 char word1 [] ="fluffy"; 

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

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

您还可以使用malloc()手动分配内存:

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

如果您事先并不知道(在编码时)arrays中将包含多少个字符串以及它们将会有多长,这是一种可行的方法。 但是当它不再使用时你将不得不释放内存(call free() )。