我正在从一本书中自学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*/
Run Code Online (Sandbox Code Playgroud)
但我不断收到消息:
crossword.c:20:16: warning: assignment makes integer from pointer without a cast [enabled by default]
Run Code Online (Sandbox Code Playgroud)
不确定是什么问题...我试图查找如何制作一个字符串数组但没有运气
任何帮助都感激不尽,
山姆
md5*_*md5 14
Run Code Online (Sandbox Code Playgroud)words_array[0]=word1;
word_array[0]是一个char,而是word1一个char *.你的角色无法持有地址.
字符串数组可能看起来像这样:
char array[NUMBER_STRINGS][STRING_MAX_SIZE];
Run Code Online (Sandbox Code Playgroud)
如果你想要一个指向字符串的指针数组:
char *array[NUMBER_STRINGS];
Run Code Online (Sandbox Code Playgroud)
然后:
array[0] = word1;
array[1] = word2;
array[2] = word3;
Run Code Online (Sandbox Code Playgroud)
也许你应该读这个.
如果你需要一个字符串数组.有两种方法:
1.二维数组字符
在这种情况下,您必须事先知道字符串的大小.它看起来如下:
// This is an array for storing 10 strings,
// each of length up to 49 characters (excluding the null terminator).
char arr[10][50];
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
声明
char words_array[3];
Run Code Online (Sandbox Code Playgroud)
创建一个包含三个字符的数组.您似乎想要声明一个字符指针数组:
char *words_array[3];
Run Code Online (Sandbox Code Playgroud)
但是你有一个更严重的问题.声明
char word1 [6] ="fluffy";
Run Code Online (Sandbox Code Playgroud)
创建一个六个字符的数组,但实际上你告诉它有七个字符.所有字符串都有一个额外的字符,'\0'用于告诉字符串的结尾.
声明数组的大小为7:
char word1 [7] ="fluffy";
Run Code Online (Sandbox Code Playgroud)
或者保留大小,编译器会自行解决:
char word1 [] ="fluffy";
Run Code Online (Sandbox Code Playgroud)
您还可以使用malloc()手动分配内存:
int N = 3;
char **array = (char**) malloc((N+1)*sizeof(char*));
array[0] = "fluffy";
array[1] = "small";
array[2] = "bunny";
array[3] = 0;
Run Code Online (Sandbox Code Playgroud)
如果您事先(在编码时)不知道数组中有多少个字符串以及它们的长度,那么这是一种方法。但是当不再使用内存时,您必须释放它(调用free())。