10

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

4 回答 4

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

也许你应该读这个

于 2013-03-01T16:01:31.173 回答
9

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

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));
于 2013-03-01T16:03:57.817 回答
8

宣言

char words_array[3];

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

char *words_array[3];

你有一个更严重的问题。宣言

char word1 [6] ="fluffy";

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

要么将数组声明为大小为 7:

char word1 [7] ="fluffy";

或者忽略大小,编译器会自己计算出来:

char word1 [] ="fluffy";
于 2013-03-01T16:02:00.650 回答
5

You can also use malloc() to allocate memory manually:

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

If you don't know in advance (at coding time) how many strings will be in an array and how lengthy they'll be, this is a way to go. But you'll have to free the memory when it's not used anymore (call free()).

于 2013-03-01T16:08:24.450 回答