-3

Hey so im trying to attempt to read in a file, store it in a hash and then copy it. However i get the incompatible pointer type

struct hash_struct {
    int id;                   
    char name[BUFFER_SIZE];            /* key (string WITHIN the structure */
    UT_hash_handle hh;         /* makes this structure hashable */
};

int main(int argc, char *argv[] )
{
    char *lines[80];
    FILE* fp = fopen("file.txt","r");
    if(fgets(*lines, BUFFER_SIZE, fp) != NULL)
    {
        puts(*lines);
        // do something
    }
    fclose(fp);
    const char **n;
    char *names[1024];
    strcpy(*names, *lines);
    struct hash_struct *s, *tmp, *users = NULL;
    int i=0;
for (n = names; *n != NULL; n++) 
{
    s = (struct hash_struct*)malloc(sizeof(struct hash_struct));
    strncpy(s->name, *n,10);
    s->id = i++;
    HASH_ADD_STR( users, name, s );
}

HASH_FIND_STR( users, "joe", s);
if (s) printf("joe's id is %d\n", s->id);
printf("Hash has %d entries\n",HASH_COUNT(users));

/* free the hash table contents */
HASH_ITER(hh, users, s, tmp) {
  HASH_DEL(users, s);
  free(s);
}
return 0;

}

The code works when i initialize const char **n, *names = {array elements here}; But it doesnt work with the code i have. Please help.

Icey
  • 1
  • 1
  • `char *lines[80];`..`if(fgets(*lines, BUFFER_SIZE, fp) != NULL)` change to `char lines[80];`..`if(fgets(lines, sizeof lines, fp) != NULL)` and `char *names[1024];strcpy(*names, *lines);` --> `char names[1024];strcpy(names, lines);//remove '\n'` – BLUEPIXY Oct 18 '14 at 22:58
  • don't write `*` if you don't konw what it means – M.M Oct 19 '14 at 02:06

1 Answers1

0

lines is declared to be an array of char pointers, but doesn't allocate any space for the strings they point to. In your working version, the compiler took care of allocating space for each string.

Plus, you can't use strcpy to copy an array of 80 pointers to an array of 1024 pointers. Instead, each line you read in needs space to be allocated for it to be read into; then the addresses of each of those can be assigned to an element of names. In fact, as @BLUEPIXY suggests, line should be an array of 80 chars, not an array of 80 pointers-to-chars. Or you could just malloc the space for each new line, and put the address of that line into names.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • I tried allocating memory using malloc but i get the same issue. The issue seems to be when the program trys to call on n or names – Icey Oct 18 '14 at 23:10
  • I tried using just BUFFER_SIZE for both the arrays but i still cant seem to get it to work. Im not understanding which pointer is not working and why. – Icey Oct 18 '14 at 23:30