I’m trying to dynamic allocate a double pointer. I intend to call a function with parameter which are file name and a address of a pointer struct variable. And the function Opens a text file and dynamic allocate as a double pointer. Because I intend to return the double pointer struct variable so the pointer variable in main() can save the value which are read by file.
These are my codes:
// main.c
// Priority Scheduling Algorithm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Priority.h"
// Sort by Arrival Time
void Sort(Process process[], int numProcess) {
Process temp;
for (int i = 0; i < numProcess; i++) {
for (int j = i + 1; j < numProcess; j++) {
if (process[i].arrivalTime > process[j].arrivalTime) {
temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}
}
int main() {
Process* process = NULL;
int numProcess = OpenFile("scheduling.txt", &process);
// List of Process
printf("inputn");
printf("---------------------------------------------------------n");
printf("Process IDt Arrival Timet Burst Timet Priorityn");
printf("---------------------------------------------------------n");
for (int i = 0; i < numProcess; i++) {
printf("%2dtt %2dtt %2dtt %2dn", process[i].processID, process[i].arrivalTime, process[i].burstTime, process[i].priority);
}
// sort by Arrival Time
Sort(process, numProcess);
// Run scheduling algorithm
SchedulingAlgorithm(process, numProcess);
free(process);
system("pause");
return 0;
}
As you can see, I call the function with file name and a address of a pointer.
// FileOpen.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Priority.h"
// File Open
int OpenFile(const char* filename, Process** process) {
FILE* file;
int line = 0;
int i = 0;
// File open
if (fopen_s(&file, filename, "r") != 0) {
printf("Failed to Open filen");
return -1;
}
char bin[50];
while (fgets(bin, sizeof(bin), file) != 0) {
line++;
}
rewind(file);
*process = (Process*)malloc(sizeof(Process) * (line + 1));
if (*process == NULL) {
fprintf(stderr, "Memory allocation failuren");
return -1;
}
while (fscanf_s(file, "%s %d %d %d %d", bin, 20, &(*process)[i].processID, &(*process)[i].arrivalTime, &(*process)[i].burstTime, &(*process)[i].priority) != EOF) {
i++;
}
fclose(file);
return line;
}
And there is the C6385 Warning at this code:
while (fscanf_s(file, "%s %d %d %d %d", bin, 20, &(*process)[i].processID, &(*process)[i].arrivalTime, &(*process)[i].burstTime, &(*process)[i].priority) != EOF) {
i++;
}
I think this warning relates with memory allocation.
I have no idea why it does not work properly because it works in MacOs.
7ib is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.