#include<stdlib.h>
#include<stdio.h>
/*
Content of Text FILE
5 // no_of_process
4 // no_of_resource_type
6 3 4 2 // vector E matrix
3 0 1 1 // 5x4 matrix
0 1 0 0
1 1 1 0
1 1 0 1
0 0 0 0
*/
int main()
{
FILE *file;
int no_of_process;
int no_of_resource_type;
int *vector_E;
int **C;
int counter = 1, i, k;
char unwanted[50];
file = fopen("file_path\\file.txt", "r");
if(file == NULL){
printf("NO SUCH A FILE EXISTS!!!");
exit(1);
}
while(!feof(file))
{
if(counter == 1){
fscanf(file, "%d", &no_of_process); // The number of process is set
fscanf(file, "100[^\n]", unwanted); // put in "unwanted" the un wanted chars untill you get \n
counter++; // counter for selecting operation type
printf("\nProcess: %d", no_of_process);
}
else if(counter == 2){
fscanf(file, "%d", &no_of_resource_type); // The number of resource type is set
fscanf(file, "100[^\n]", unwanted); // put in "unwanted" the un wanted chars untill you get \n
counter++; // counter for selecting operation type
printf("\nType: %d\n", no_of_resource_type);
}
else if(counter == 3){
vector_E = (int *)malloc(sizeof(int)*no_of_resource_type); // Allocating memory for vector_E of size # of resource type
for(i=0; i<no_of_resource_type; i++){ // fillling vector_E array
fscanf(file, "%d", &vector_E[i]);
printf("%d ", vector_E[i]);
}
fscanf(file, "100[^\n]", unwanted); // put in "unwanted" the un wanted chars untill you get \n
counter++; // counter for selecting operation type
printf("\n");
}
else if(counter == 4){
C = (int**)malloc(sizeof(int *)*no_of_process); // Allocating memory for Current Allocation Matrix "part1"
for(i=0; i<no_of_resource_type; i++) // Allocating memory for Current Allocation Matrix "part2"
C[i] = (int *)malloc(sizeof(int)*no_of_resource_type);
for(i=0; i<no_of_process; i++){ // Filling the Current Allocation Matrix
for(k=0; k<no_of_resource_type; k++){
fscanf(file, "%d", &C[i][k]);
printf("%d ", C[i][k]);
}
printf("\n");
// -------------------------------------------------------------------- ???????????
// Problem is here !!!!!
// --------------------------------------------------------------------- ???????????
fscanf(file, "100[^\n]", unwanted); // put in "unwanted" the un wanted chars untill you get \n
}
}
}
printf("# of Process: %d\n", no_of_process);
printf("# of Resource Type: %d\n", no_of_resource_type);
printf("Vector E\n");
for(i=0; i<no_of_resource_type; i++)
printf("%d ", vector_E[i]);
printf("\nCurrent Allocation Matrix\n");
for(i=0; i<no_of_process; i++){
for(k=0; k<no_of_resource_type; k++){
printf("%d ", C[i][k]);
}
printf("\n");
}
system("pause");
return 0;
}
任务是从 txt 文件中读取数字。读取no_of_process、no_of_resource_type和vector_E矩阵没有问题。当程序读取“5x4 矩阵”的第 4 行并出现“程序中引发的访问冲突(分段错误)”错误时,就会出现问题。我将出现问题的行标记为“问题在这里!!!”。
有人可以解释这个问题的原因是什么以及如何解决它?