簡體   English   中英

將數組放入Dev-cpp的頭文件中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM