I have an assignment in CS class with the description as follows but I am having a hard time to dynamically allocating memory, please help me, I have to submit my code today.
I have a structure as follows:
typedef struct sample{
char* name;
int list_len;
float* value_list;
}sample;
I need to dynamically allocate memory while reading the file.
Read a file (created in a text editor – pico) of delimited Sample data records into an array of pointers to your sample structs. Note: you may use a statically sized array of size 1024, however, each element of the array must be a pointer to a sample struct (as defined above). Initially, each element of the array must be set to NULL (to indicated that it is not used), and then later to a dynamically allocated sample struct if it is to be used.
Note: after dynamically allocating memory for a sample struct, you have enough memory for each/every component of the structure. However, for each component of that structure that is a pointer, I will eventually need to allocate memory for the “thing” that it points to as well (think string via char*, array via float*). You will also have to remember this when freeing memory via a pointer to a sample struct.
I have this so far and I am trying to use strtok to parse through the list.
void readfile(){
int SIZE = 1024;
sample* arr[SIZE] = {NULL};
FILE* fin;
sample* sample;
fin = fopen("sample.txt", "r");
if (fin == NULL) {
printf("sample.txt could not be opened"\n");
exit(1);
}
else
fgets(arr, SIZE, fin);
while(fin != EOF){
sample = (sample*)malloc(sizeof(sample);
}
}
while(fin != EOF)
is totally wrong – Chris Turnerstrtok()
. Post thestrtok()
code attempt. – chux - Reinstate Monicaelse fgets(arr, SIZE, fin); while(fin != EOF) { ...
-->else { while (fgets(arr, SIZE, fin)) { ...
– chux - Reinstate Monica