Global arrays, file I/O and pointers
Hi there, I'm a programming newbie and I can't seem to get this section of code to work. I read in the lines of a file, but immediately after the loop that creates an array of the strings in the file, all char pointers point to the last item in the list.
Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef char * string;
string *dictionary;
int num_lines;
void *thread1(char *input_word){
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
void *thread2(char *input_word){
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
main(){
//count number of words in dictionary file
FILE *input = fopen("dictionary.txt","r");
num_lines=0;
char temp[50];
while (fscanf(input,"%s",temp)!=EOF) num_lines++;
rewind(input);
//create a 1D array containing the words from the dictionary
dictionary=malloc(sizeof(char*)*num_lines);
int x;
for(x=0;x<num_lines;x++)
dictionary[x]=malloc(sizeof(char)*20);
num_lines=0;
while (fscanf(input,"%s",temp)!=EOF){
dictionary[num_lines]=temp;
num_lines++;
//array properly lists words here
}
//but out here all dictionary[x] locations contain the last line in the file.
//scan for the input word
char *user_Input=NULL;
int test;
user_Input=malloc(sizeof(char)*20);
while(1){
printf("Enter a string: ");
scanf("%s",user_Input);
if(strcmp(user_Input,"exit")==0) break;
pthread_t t_1,t_2;
if(test = pthread_create(&t_1, NULL, (void *(*)(void *))thread1, user_Input))
printf("Thread 1 creation failure.\n");
if(test = pthread_create(&t_2, NULL, (void *(*)(void *))thread2, user_Input))
printf("Thread 2 creation failure.\n");
pthread_join(t_1, NULL);
pthread_join(t_2, NULL);
}
free(user_Input);
}
Thanks for any advice you may have!!!