【发布时间】:2015-09-15 19:09:21
【问题描述】:
目标:
- 鉴于大小只能在函数
load()中计算,请创建字符串(字典)的全局数组。 - 使用函数
print()在屏幕上打印字典。
我的做法:
创建指向字符串的全局指针,在load() 中创建字符串数组并将本地数组分配给全局指针。
问题:
如果我尝试在load() 内打印全局数组(以及本地数组),一切都很好,但如果使用print() 打印,则在数组末尾的某处会出现段错误。 GDB 和 valgrind 输出对我来说似乎很神秘。我放弃。怎么了?
来源和字典是here。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// length of the longest word in dictionary
#define LENGTH 45
// dictionary file
#define DICTIONARY "large"
// prototypes
void load(const char* dictionary);
void print(void);
// global dictionary size
int dict_size = 0;
// global dictionary
char **global_dict;
int main(void)
{
load(DICTIONARY);
print();
return 0;
}
/**
* Loads dictionary into memory.
*/
void load(const char* dictionary)
{
// open dictionary file
FILE *dict_file = fopen(dictionary, "r");
// compute size of dictionary
for (int c = fgetc(dict_file); c != EOF; c = fgetc(dict_file))
{
// look for '\n' (one '\n' means one word)
if (c == '\n')
{
dict_size++;
}
}
// return to beginning of file
fseek(dict_file, 0, SEEK_SET);
// local array
char *dict[dict_size];
// variables for reading
int word_length = 0;
int dict_index = 0;
char word[LENGTH + 1];
// iteration over characters
for (int c = fgetc(dict_file); c != EOF; c = fgetc(dict_file))
{
// allow only letters
if (c != '\n')
{
// append character to word
word[word_length] = c;
word_length++;
}
// if c = \n and some letters're already in the word
else if (word_length > 0)
{
// terminate current word
word[word_length] = '\0';
//write word to local dictionary
dict[dict_index] = malloc(word_length + 1);
strcpy(dict[dict_index], word);
dict_index++;
// prepare for next word
word_length = 0;
}
}
// make local dictioinary global
global_dict = dict;
}
/**
* Prints dictionary.
*/
void print(void)
{
for (int i = 0; i < dict_size; i++)
printf("%s %p\n", global_dict[i], global_dict[i]);
}
【问题讨论】:
-
我只知道unpure c的答案。
-
这应该是格式最简洁的问题之一。
-
@WedaPashi 它是由 OP 形成的,但用户也将它塑造成 @MohitJain。
-
是的,我看到了编辑历史。做得很好@MohitJain
-
1) 始终检查 (!=NULL) fopen() 的返回值以确保操作成功。 2) 始终检查 (!=-1) fseek() 的返回值以确保操作成功。 3) 始终检查 (!=NULL) malloc() 的返回值以确保操作成功
标签: c arrays string variables segmentation-fault