My task is to count how many distinct words I have in a file using C. I already did the same assignment in Java but I have some difficulties doing this in C. I've read a lot about pointers and arrays and how to initialize them in the constructor but I still don't get it, that's why I'm asking for help.
This is how I do it in Java:
public class DataSet { private String[] elements; private int top; public DataSet() { elements = new String[1]; top = 0; } And now I'm trying to do the same thing in C and this is how my code looks like:
I have two classes the first one DataSet.h:
typedef struct _DataSet { char *elements; int top; } DataSet; and the second one DataSet.c
#include <stdlib.h> #include <stdio.h> #include "DataSet.h" /*external libaray */ DataSet* createDataSet() { DataSet* d = malloc(sizeof(TextString)); d -> elements = malloc(1 * sizeof(char)); d -> top = 0; return d; } I have 2 questions:
- are my understanding correct: I create an object DataSet in order to be able use the variables, then I set the pointer to this new array called elements which might contain one string, then I set the top to 0 and in the end i return the object.
- if it's not correct what should I do in order to make it exactly the same as my Java code?
char*or a pointer tochar*which would then be allocated an arraysizeof(char); it's always 1 by spec. Good for not casting the return frommalloc.TextString? C doesn't have classes.[java]tag as the answer won't be about Java.m not sure that this is the correct way to do it in C. Ive read a lot of explanations how to make String Array in C and in all of them, they use the word char instead of String (because there is no possibility to use the word String in C as a data type)