[英]Putting arrays into header files in Dev-cpp
这是我的头文件,该文件基本上从列表中生成一个随机单词,然后查找单词的长度,然后将信息发送回主代码。
int WordDevelopment()
{
char words[10][15] =
{
"seanna",//6 //0
"yellow",//6 //1
"marshmallow",//11 //2
"potato",//6 //3
"beach",//5 //4
"icecream",//8 //5
"seven",//5 //6
"giraffe",//7 //7
"random",//6 //8
"xylophone",//9 //9
};
//Generates random word
srand (time(NULL));
int randomIndex = rand() % 10;
int x = 0;
int a;
int randvar = 0;
randvar = rand();
randomIndex = randvar % 10;
printf("Row: %d\n",randomIndex);
//Stores the whole word in the word array
char word[15];
for(a=0; a<15; a++)
{
word[a]=words[randomIndex][a];
}
printf("word: %s\n",word);
//Finds the word length
int wordlength = strlen(words[randomIndex]);
printf("word length: %d\n",wordlength);
}
我想知道如何正确地将数组放在此头文件的顶部,并能够在我的主代码中访问头文件中的变量。
头文件旨在包含不同源文件使用的变量和函数原型的声明 。
在头文件中,您将变量声明为extern:
header.h:
extern char word[15];
然后,实际定义变量字的源文件和引用该变量字的源文件必须在开头包含header.h :
source1.c:
#include "header.h"
要使变量字可见,可以将其声明为全局变量,例如,可以在main.c文件中对其进行定义:
#include <stdio.h>
....
#include "header.h"
char word[15];
然后,它对所有链接的其他对象都是可见的。
有关进一步的说明,请参见此帖子 。
我不确定我是否完全理解您在代码中要做什么(我希望只是测试代码或练习),但是,如果您只需要使可变单词 (而不是word )可见,那么我会在包含main()的文件中定义两者。 在头文件中将单词声明为全局和外部。
主源文件应如下所示:
#include <stdio.h>
....
#include "header.h"
char word[15];
int main () {
...
char words[10][15] = { "seanna", "yellow", "marshmallow", "potato", "beach", "icecream", "seven", "giraffe", "random", "xylophone" };
...
for(a = 0; a < 15; a++)
{
word[a] = words[randomIndex][a];
}
...
return 0;
}
如果您只需要从数组单词中挑选一个随机单词,那么最好使用以下方法:
char *words[10] = { "seanna", "yellow", "marshmallow", "potato", "beach", "icecream", "seven", "giraffe", "random", "xylophone" };
char *word;
int main()
{
int idx = -1;
srand (time(NULL));
idx = rand() % 10;
printf("Row: %d\n", idx);
//Stores the whole word in the word array
word = one_word(idx);
printf("word: %s\n", word);
//Finds the word length
int wordlength = strlen(word);
printf("word length: %d\n", wordlength);
return 0;
}
当单词被定义并分配为字符串文字数组时,您不必指定大小,它将自动计算大小并添加nul(终止)字符。 然后,如果您不需要修改单词,则可以仅使用指向当前提取单词的指针。 否则要复制该单词,建议您使用memcpy(不要一次复制一个字符)。
word = malloc(16 * sizeof(char)); // 15 + 1 for the terminating char
wordlen = strlen(words[idx]) + 1; // copy also the terminating char
memcpy(word, words[idx], wordlen * sizeof(char))
(这里您应该删除sizeof(char),因为它将始终为1,我把它放在这里只是为了表明memcpy需要size_t字段)
在单词和单词上方都声明为全局单词,并且如果在引用它们的那些文件中,您在开始时将它们声明为extern (或如上所述使用头文件),则所有函数以及其他源文件都将看到它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.