c - 从 C 中的函数返回字符串数组

标签 c arrays string

我将给定文件(字典)中的单词读入单个字符串,并将该字符串分配给字符串数组的第 n 个索引。但它不起作用。 main() 中 for 循环的输出始终为 e3V\347 等,createWordTable() 中 for 循环的输出为永远是字典的最后一个词。这是我的代码

char** createWordTable();

char** createTable();

int main()
{

    int i;
    char **hashTable;
    hashTable = createTable();
    hashTable = createWordTable();



    for (i=0; i< 338; i++) {
        printf("%s \n",hashTable[i]);
    }

    return 0;
}

char** createWordTable(){

    char  word[20],**table;
    FILE *dicFile;
    table = createTable();

    dicFile = fopen("smallDictionary.txt", "r");
    if (dicFile == NULL) {
        perror("error");
    }
    int wordCount = 0,endFile = 1;
    while (endFile != EOF) {
        endFile = fscanf(dicFile,"%s",word);
        table[wordCount] = word;
        wordCount = wordCount+1;
    }
    for (int i=0; i< 338; i++) {
        printf("%s \n",table[i]);
    }
    return table;

}

char** createTable(){

    char **table;
    int i;
    table = (char **)malloc(338 * sizeof(char *));
    for (i=0; i<=338; i++) {
        *table = (char *)malloc(25 * sizeof(char));
    }
    return table;
}

我将代码更改为此及其工作!我定义了全局变量“table”并删除了指针(也是动态分配函数)。我很好奇为什么指针不适用于此代码的 C 中的字符串数组(我知道方括号也表示“指针”)?因为我对整数数组没有不好的经验。抱歉英语不好,这是新代码:`

字符词[338][10];

主要内容()

{

createWordTable();

for (int i=0; i< 338; i++) {
    printf("%s \n",words[i]);
}


return 0;

void createWordTable(){

char  word[20];

FILE *dicFile;


dicFile = fopen("smallDictionary.txt", "r");
if (dicFile == NULL) {
    perror("error");
}
int wordCount = 0;
while (!feof(dicFile)) {
    fscanf(dicFile,"%s",word);
    if(feof(dicFile)) break; 
   strcpy(words[wordCount], word);

    wordCount = wordCount+1;
}

 fclose(dicFile);

}`

最佳答案

您正在丢失 createTable() 结果。将其存储为单独的指针变量。

hashTable = createTable();
hashTable = createWordTable();

关于c - 从 C 中的函数返回字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19888582/

相关文章:

c - 首先通过套接字发送我要发送的文件的大小

python - 如何修复 ZigZag 问题中的 'list index out of range' 错误?

C:使用循环替换字符串中的子字符串

ruby - ruby 中的字符串替换方法有什么用?

c - 字符串指针问题,未正确指向

c - 编译错误问题

java - 如何管理多页的 3D 数组初始化?

c - 没有pointee指针不返回null?

java - 以编程方式在 TextView 中设置文本的正确方法

c - C 中动态帐户连接的最佳解决方案?