I am reading in a text file containing 10 rows and 3 columns. Each element needs to be put into an array for further manipulation. The fileToArray method will single out each string and i can successfully print each string individually however I cannot seem to assign the strings to each index correctly.
My understanding is that i have a pointer to 10 dataArrays and in my switch statement what essentially happens is dataArray[0].pName = P1 ... dataArray[1].pName = P2 ... etc... and similarly for the other variables in the struct.
The text file has a max of 10 rows hence why 10 arrays are initialized.
Is my understanding flawed or is there some blatant errors in my code?
struct Processes
{
char *pName;
char *arvTime;
char *srvTime;
};
void fileToArray(FILE *fp, struct Processes dataArray[])
{
// temp[14] because 14 is the max size a line can be
char temp[14];
char delim[] = " \n";
int count = 0;
int a, b, c = 0;
while(fgets(temp, 14, fp) != NULL)
{
char *ptr = strtok(temp, delim);
while(ptr != NULL)
{
// printf("'%s'\n", ptr);
// ^^^^ This line will successfully print out each string
switch(count)
{
case 0:
dataArray[a].pName = malloc(strlen(ptr + 1));
strcpy(dataArray[a].pName, ptr);
a++;
count++;
free(dataArray[a].pName);
break;
case 1:
dataArray[b].arvTime = malloc(strlen(ptr + 1));
strcpy(dataArray[b].arvTime, ptr);
b++;
count++;
free(dataArray[b].arvTime);
break;
case 2:
dataArray[c].srvTime = malloc(strlen(ptr + 1));
strcpy(dataArray[c].srvTime, ptr);
c++;
count = 0;
free(dataArray[c].srvTime);
break;
}
ptr = strtok(NULL, delim);
}
}
}
int main(int argc, void *argv[])
{
struct Processes dataArray[10];
if(argc == 1)
{
FILE *fp;
fp = fopen("process-data.txt", "r");
fileToArray(fp, dataArray);
fclose(fp);
}
return 0;
}
// Sample text file being read //
P1 1 5
P2 2 2
P3 11 5
P4 17 9
P5 3 1
P6 10 10
P7 4 3
P8 4 1
P9 7 8
P10 5 4
Running this code results in a segfault and i am unsure as to why. Looking at other similar posts the solution seems to be not using malloc() which makes me think i have implemented the function incorrectly.
int main(int argc, void *argv[])isn't a valid definition of main -- your choices areint main(void)orint main(int argc char *argv[])/char** argvfreethe data after having copied the strings to it? Now there is no storage allocated to it anymore. Trying to access it (which you don't show) will cause the seg fault.int a, b, c = 0;only initializes c to 0.aandbare not initialized, IOW they will initially contain an indeterminate value. You probably want this:int a = 0, b = 0, c = 0;