0
votes

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);
        }


 }
1
while(fin != EOF) is totally wrongChris Turner
"I am trying to use strtok" --> This is unclear. Code does not have strtok(). Post the strtok() code attempt.chux - Reinstate Monica
else fgets(arr, SIZE, fin); while(fin != EOF) { ... --> else { while (fgets(arr, SIZE, fin)) { ...chux - Reinstate Monica

1 Answers

0
votes

Just concentrating on your memory question and ignoring all other errors in your code:

sample* arr[SIZE] = {NULL};

So you have an array of pointes to samples. The following statement will not compile because sample is not a variable, however, you are close:

sample = (sample*)malloc(sizeof(sample);

All you need is a buffer to read the line and a variable to keep track of where you are in the array:

     int i= 0;
     char linebuf[1024];
     while (fgets(linebuf, 1024, fin) && i<SIZE) {
         arr[i]= malloc(sizeof(sample));
         // now parse the linebuf and fill arr[i] with it
         i++;
    }