我使用以下代码在堆上加载一个大型哈希表。 但是我不知道加载后搜索整个数组的正确语法。
我想我可以在最后一个 J 循环中添加一个 strcmp??
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int lines_allocated = 128;
int max_line_len = 100;
/* Allocate lines of text */
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
if (words==NULL)
{
fprintf(stderr,"Out of memory (1).\n");
exit(1);
}
FILE *fp = fopen("hashtable.txt", "r");
if (fp == NULL)
{
fprintf(stderr,"Error opening file.\n");
exit(2);
}
int i;
for (i = 0; 1; i++)
{
int j;
/* Have we gone over our line allocation? */
if (i >= lines_allocated)
{
int new_size;
/* Double our allocation and re-allocate */
new_size = lines_allocated*2;
words = (char **)realloc(words,sizeof(char*)*new_size);
if (words == NULL)
{
fprintf(stderr,"Out of memory.\n");
exit(3);
}
lines_allocated = new_size;
}
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
if (words[i] == NULL)
{
fprintf(stderr,"Out of memory (3).\n");
exit(4);
}
if (fgets(words[i], max_line_len-1,fp) == NULL)
break;
/* Get rid of CR or LF at end of line */
for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r')j--);
words[i][j] = '\0';
}
int j;
for(j = 0; j < i; j++)
printf("%s\n", words[j]);
// Search for a string e.g "ffffffffff999999999922222222227777777777" in words[]
//
//strcmp ( string, words[j])????
//
//
//
/* Good practice to free memory */
for (;i>=0;i--)
free(words[i]);
free(words);
return 0;
}
我尝试在循环中实现 strcmp 但程序出现段错误。 使用这个例子:
/* what is i? the number of items used in the array? */
for(x = 0; x < i; x++) {
if ( strcmp( new_name, names[x] ) == 0 ){
/* match, x is the index */
return x;
}
}
/* here with no match */
return -1;
最佳答案
当我缩进你的代码时,我看到:
for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || Words[i][j] == '\r')j--);
我想你的意思是:
for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || Words[i][j] == '\r'); j--)
----^^^^^^^^
那个 while 永远不会执行大括号之间的内容。
关于arrays - C 在堆数组中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26779881/