Hello all,
I have been trying to write this program that reads a file of courses and then stores only the unique courses in an array of strings.
for some reason it crashes while reading the 2nd line.
printf within the function are just for me trying to trace the problem.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** uniqueCourses(FILE *fp, int *wordCount);
int main()
{
FILE* fp;
char** in;
int i =0;
int n =0;
int* w = &n;
fp = fopen("data.txt","r");
in = uniqueCourses(fp,w);
for (i=0; i <3; i++)
{
printf("%s",in[i]);
}
return 0;
}
char** uniqueCourses(FILE *fp, int *wordCount)
{
char* del = ",";
char* token;
char buffer[100];
char** myArray;
myArray = malloc(50* sizeof(char*));
int i = 0;
int v=0;
int flag =0;
int count = 0;
while(fgets(buffer,sizeof(buffer),fp) != NULL)
{
token = strtok(buffer,del);
while(token != NULL)
{
if (count == 0)
{
myArray[i] = malloc(10 * sizeof(char));
strcpy(myArray[i],token);
}
for (v =0; v<count; v++)
{
if (strcmp(myArray[v],token) == 0)
{
flag = 1;
break;
}
}
printf("2");
/* if not then store it in our main array */
if (flag != 1 )
{
i++;
myArray[i]= malloc(10 * sizeof(char));
strcpy(myArray[i],token);
printf("%s",myArray[i]);
}
printf("3");
count++;
token = strtok(NULL,del);
}
printf("1");
}
return myArray;
}