How to store strings in a 2D array in C? - arrays

I want to store strings in a char * array but I don't know how I can do that.
Each cell in the 2d array can contain letters or numbers with 2 digits.
|_|S|_|
|_|10|_|
|_|W|_|
|_|_|_|
|_|_|_|
I tried this, I used struct:
struct Etage {
char Idsalles[20];
int** etage;
int width;
int height;
};
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "etage.h"
#define COLS 15
#define ROWS 9
Etage *createMap()
{
Etage *e = malloc(sizeof(Etage));
e->width = COLS; // columns
e->height = ROWS; // rows
e->etage = malloc(sizeof(char *) * e->height);
for (int i = 0; i < e->height; i += 1)
{
e->etage[i] = malloc(sizeof(char) * e->width);
for (int j = 0; j < e->width; j += 1)
{
e->etage[i][j] = "0";
}
}
return e;
}
void randomId(Etage *e, int maxSalles)
{
srand(time(NULL));
int i = 0;
if (maxSalles < 10)
{
printf("Seulement %d disponibles, veuiller générer plus de salles.\n", maxSalles);
return;
}
while (i < 10)
{
int id = (rand() % maxSalles) + 1;
int existe = testId(e, id);
if (existe != 1)
{
e->Idsalles[i] = id;
i += 1;
}
}
return;
}
int testId(Etage *e, int id)
{
for (int i = 0; i < 10; i += 1)
{
if (id == e->Idsalles[i])
{
return 1;
}
}
return 0;
}
void printEtage(Etage *e)
{
for (int i = 0; i < e->height; i += 1)
{
for (int j = 0; j < e->width; j += 1)
{
if(e->etage[i][j] == 0){
printf(" ");
}else{
printf("%s", e->etage[i][j]);
printf(" ");
}
}
printf("\n");
}
printf("Id des salles de cette étage: ");
for(int i =0; i <10;i+=1){
printf("%d ",e->Idsalles[i]);
}
printf("\n");
}
void freeEtage(Etage *e)
{
//free(e->etage);
free(e);
}
void placerSalles(Etage* e){
int a=ROWS/2;
int b=COLS/2;
//0 = Haut; 1 = Droite; 2 = Bas; 3 = Gauche
e->etage[a][b] = e->Idsalles[0]+"\0"; // On place la premiere salle au centre de l'étage sa sera le spawner 'S'
srand(time(NULL));
int i = 1;
while(i<10){
int dir = randomDirections();
if(dir==0){ // On se déplace en haut
a = a-1; //On se déplace
if(e->etage[a][b] == 0 && a > 0){
e->etage[a][b] = e->Idsalles[i]+"\0";
i+=1;
}else{
a = a+1; // Sionon on revien a la derniere case connu
}
}else if(dir==1){ // On se déplace à droite
b=b+1;
if(e->etage[a][b] == 0 && b< e->width){
e->etage[a][b] = e->Idsalles[i]+"\0";
i+=1;
}else{
b = b-1;
}
}else if(dir==2){ // On se déplace en bas
a = a+1;
if(e->etage[a][b] == 0 && a>e->height){
e->etage[a][b] = e->Idsalles[i]+"\0";
i+=1;
}else{
a = a-1;
}
}else if(dir==3){ // On se déplace à gauche
b = b-1;
if(e->etage[a][b] == 0 && b>0){
e->etage[a][b] = e->Idsalles[i]+"\0";
i+=1;
}else{
b = b+1;
}
}
}
}
int randomDirections(){
int i = 0;
int id = rand() % 4; // Remplacé 10 par le nbrSalles
//printf("Position: %d\n",id);
return id;
}
I have a good understanding with 2d array but three...
I tried using malloc.
I don't even think this is possible...

If your string is a maximum of 2 characters long (your strings will be 3 chars long)
char array[rows][cols][3] = {{"2", "a", "34"}, ... };
or to use malloc
char (*array)[cols][3] = malloc(rows * sizeof(*array));

Related

Can't find the segmentation error in my code

So, i am trying to re-create the Conway Game of Life and i have a segmentation error in my code that i can't find.
i've read it several times and i can't understand where does the error come from, i know that it has to do with array but i can't find where
Code :
#ifndef _DEFAULT_SOURCE
# define _DEFAULT_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define LIGNES 27
#define COLONNES 37
#define CELLULE_EN_VIE '#'
#define CELLULE_MORTE '.'
void effaceConsole(void);
void attendre(double duree);
void afficheMatrice(const char matrice[][COLONNES]);
void videMatrice(char matrice[][COLONNES]);
void copieMatrice(const char src[][COLONNES], char dest[][COLONNES]);
int initialiseMatrice(char matrice[][COLONNES], int choixInit);
int verifieCellule(const char copie[][COLONNES], int ligne, int colonne);
int compteVoisinsEnVie(const char copie[][COLONNES], int ligne, int colonne,
int typePavage);
char nouvelEtatCellule(char etatCellule, int nbVoisinsEnVie, int typePavage);
int metAjourMatrice(char matrice[][COLONNES], char copie[][COLONNES],
int typePavage);
void boucleEvenement(int epoques);
int saisieChoixInit(void);
int saisieTypePavage(void);
int main(void)
{
int epoques;
printf(
"Bonjour, Merci de rentrer le nombre d'époques sur lesquelles vous "
"voulez laisser marcher le programme\n");
printf("Le nombre d'époque : ");
scanf("%d", &epoques);
printf("C'est bon");
boucleEvenement(epoques);
return 0;
}
void effaceConsole(void)
{
if(system("clear") != 0) {
printf("La console n'a pas pu etre effacee...\n");
}
}
void attendre(double duree)
{
usleep(duree * 1000000.);
}
void afficheMatrice(const char matrice[][COLONNES])
{
for(int i = 1; i < LIGNES - 1; i++)
{
for(int y = 1; y < COLONNES - 1; y++)
{
printf(" %c ", matrice[i][y]);
}
printf("\n");
}
}
void videMatrice(char matrice[][COLONNES])
{
for(int i = 0; i < LIGNES; i++)
{
for(int y = 0; y < COLONNES; y++)
{
matrice[i][y] = CELLULE_MORTE;
}
}
}
void copieMatrice(const char src[][COLONNES], char dest[][COLONNES])
{
for(int i = 0; i < LIGNES; i++)
{
for(int y = 0; y < COLONNES; y++)
{
dest[i][y] = src[i][y];
}
}
}
int initialiseMatrice(char matrice[][COLONNES], int choixInit)
{
videMatrice(matrice);
if(choixInit == 1) // Blinker
{
matrice[13][17] = CELLULE_EN_VIE;
matrice[13][18] = CELLULE_EN_VIE;
matrice[13][19] = CELLULE_EN_VIE;
}
if(choixInit == 2) // Toad
{
matrice[14][16] = CELLULE_EN_VIE;
matrice[14][17] = CELLULE_EN_VIE;
matrice[14][18] = CELLULE_EN_VIE;
matrice[13][17] = CELLULE_EN_VIE;
matrice[13][18] = CELLULE_EN_VIE;
matrice[13][19] = CELLULE_EN_VIE;
}
if(choixInit == 3) // Beacon
{
matrice[11][15] = CELLULE_EN_VIE;
matrice[11][16] = CELLULE_EN_VIE;
matrice[12][15] = CELLULE_EN_VIE;
matrice[14][17] = CELLULE_EN_VIE;
matrice[14][18] = CELLULE_EN_VIE;
matrice[13][18] = CELLULE_EN_VIE;
}
if(choixInit == 4) // Glider
{
matrice[14][16] = CELLULE_EN_VIE;
matrice[14][17] = CELLULE_EN_VIE;
matrice[14][18] = CELLULE_EN_VIE;
matrice[13][18] = CELLULE_EN_VIE;
matrice[12][17] = CELLULE_EN_VIE;
}
if(choixInit == 5) // Pentadecathlon
{
matrice[6][17] = CELLULE_EN_VIE;
matrice[7][16] = CELLULE_EN_VIE;
matrice[7][17] = CELLULE_EN_VIE;
matrice[7][18] = CELLULE_EN_VIE;
matrice[10][16] = CELLULE_EN_VIE;
matrice[10][17] = CELLULE_EN_VIE;
matrice[10][18] = CELLULE_EN_VIE;
matrice[12][16] = CELLULE_EN_VIE;
matrice[13][16] = CELLULE_EN_VIE;
matrice[12][18] = CELLULE_EN_VIE;
matrice[13][18] = CELLULE_EN_VIE;
matrice[15][16] = CELLULE_EN_VIE;
matrice[15][17] = CELLULE_EN_VIE;
matrice[15][18] = CELLULE_EN_VIE;
matrice[18][16] = CELLULE_EN_VIE;
matrice[18][17] = CELLULE_EN_VIE;
matrice[18][18] = CELLULE_EN_VIE;
matrice[19][17] = CELLULE_EN_VIE;
}
return 0;
}
int verifieCellule(const char copie[][COLONNES], int ligne, int colonne)
{
if(copie[ligne][colonne] == CELLULE_EN_VIE)
{
return 1;
}
else
{
return 0;
}
}
int compteVoisinsEnVie(const char copie[][COLONNES], int ligne, int colonne,
int typePavage)
{
int voisin[16] = {ligne - 1, colonne - 1, ligne - 1, colonne,
ligne - 1, colonne + 1, ligne, colonne - 1,
ligne, colonne + 1, ligne + 1, colonne - 1,
ligne + 1, colonne, ligne + 1, colonne + 1};
int nombre_voisin = 0;
for(int aozeiu = 0; aozeiu < 8; aozeiu = aozeiu + 2)
{
if(verifieCellule(copie, voisin[aozeiu], voisin[aozeiu + 1]) == 1)
{
nombre_voisin = nombre_voisin + 1;
}
}
return nombre_voisin;
}
char nouvelEtatCellule(char etatCellule, int nbVoisinsEnVie, int typePavage)
{
if(nbVoisinsEnVie < 2 || 3 < nbVoisinsEnVie)
{
etatCellule = CELLULE_MORTE;
}
if(nbVoisinsEnVie == 3)
{
etatCellule = CELLULE_EN_VIE;
}
else
{
etatCellule = etatCellule;
}
return etatCellule;
}
int metAjourMatrice(char matrice[][COLONNES], char copie[][COLONNES],
int typePavage)
{
copieMatrice(matrice, copie);
for(int i = 1; i < LIGNES - 1; i++)
{
for(int y = 1; y < COLONNES - 1; y++)
{
int Nombre_Voisins = compteVoisinsEnVie(matrice, i, y, 0);
matrice[i][y] = nouvelEtatCellule(matrice[i][y], Nombre_Voisins, 0);
}
}
return 0;
}
void boucleEvenement(int epoques)
{
printf("C'est bon");
char matrice[LIGNES][COLONNES], matrice_copie[LIGNES][COLONNES];
printf("C'est bon");
videMatrice(matrice);
copieMatrice(matrice, matrice_copie);
int choix = saisieChoixInit();
int pavage = saisieTypePavage();
initialiseMatrice(matrice, choix);
for(int boucle = 0; boucle < epoques; boucle++)
{
effaceConsole();
afficheMatrice(matrice);
printf("L'époque actuelle est : %d\n", epoques);
metAjourMatrice(matrice, matrice_copie, pavage);
attendre(1);
}
}
int saisieChoixInit(void)
{
printf(
"Bonjour merci de saisir le numéro de l'illustration que vous "
"souhaitez\n");
printf(
"Séléctionnez parmis ces choix :\n0) Clignotant/Blinker\n1) "
"Grenouille/Toad\n2) Phare/Beacon\n3) Planeur/Glider\n4) "
"R-pentodomino\n5) Pentadecathlon\n6) Configuration aléatoire \n");
printf("Votre choix : ");
int choix = 0;
scanf("%d\n", &choix);
return choix;
}
int saisieTypePavage(void)
{
printf("Merci de rentrer le type de pavage\n");
printf("0) Carré standart\n1) Hexagonal\n");
int pavage = 0;
printf("Votre choix : ");
scanf("%d\n", &pavage);
return pavage;
}
I re-read my code and tried to find the error, but can't find it.
The program crash as soon as i have entered the epoques in the scanf at the very beginning.

Why mi i, j, k values are broken? The values they take are not related with the range that they could have

I'm struggling with this code, its purpose is to accumulate data from a .dat file with structs that have information about marks, age, gender. When I compile it, an error shows that say "segmentation fault", I wrote a printf to show me the value of i, j and k; because I think them are the problem, here is the code and a photo of the failure:
`
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int i = 0, j = 0, k = 0;
struct persona {
int edad; //EDAD DE 12-65//
int notas; //NOTAS DE 0-10//
char sexo; //SEXO 1=MASCULINO Y 2=FEMENINO//
char exi; //EXI 1=SI 2=NO
};
struct reg {
int notas;
int contex;
int cont;
};
struct reg A[7][6][3];
int grupoedad(struct persona p) {
if( p.edad < 12) {
printf("\nexiste un error en la edad");
} else if(p.edad < 16) {
return 1;
} else if(p.edad < 26) {
return 2;
} else if(p.edad < 36) {
return 3;
} else if(p.edad < 46) {
return 4;
} else if(p.edad < 56) {
return 5;
} else if(p.edad < 66) {
return 6;
}
}
int niveling(struct persona p) {
if(p.notas < 2) {
return 1;
} else if(p.notas < 4) {
return 2;
} else if(p.notas < 6) {
return 3;
} else if(p.notas < 8) {
return 4;
} else if(p.notas <=10) {
return 5;
}
}
int femasc(struct persona p) {
if(p.sexo == 'M'){
return 1;
} else if(p.sexo == 'F') {
return 2;
}
}
void etario(int j, char grupoed[10]) //ASIGNAMOS LOS RANGOS ETARIOS//
{
switch(j)
{
case(1):
strcpy(grupoed, "12-15");
break;
case(2):
strcpy(grupoed, "16-25");
break;
case(3):
strcpy(grupoed, "26-35");
break;
case(4):
strcpy(grupoed, "36-45");
break;
case(5):
strcpy(grupoed, "46-55");
break;
case(6):
strcpy(grupoed, "56-65");
default:
printf("\nHa ocurrido un error");
}
}
//void matrizcero(struct reg A[7][6][3], int i, int j, int k) {
// for (i = 1; i < 7; i++)
// {
//for (j = 1; j < 6; j++)
// {
// for (k = 1; k < 3; k++)
// {
// A[i][j][k].contex = 0;
// A[i][j][k].cont = 0;
//A[i][j][k].notas = 0;
// }
// }
// }
// }
int main() {
struct reg {
int notas;
int contex;
int cont;
};
struct reg A[7][6][3];
struct persona p;
int rangomay, rangomen, rangointmay, resmay, resmen, jex, jmay, jmen, NIV, GRUPOET, sexo, cantidadM, califM, cantidadF, califF, grupoetario;
// matrizcero(A[7][6][3], i, j, k);
char grupoed[10];
float prom_m, prom_f;
FILE *entrada; //ABRO ARCHIVO
entrada=fopen("datospersonas.txt","ab");
if (entrada == NULL){
exit(1);
printf("\nError al abrir el archivo");
}
else {
printf("\nArchivo abierto exitosamente!");
}
while(!(feof(entrada))){
fread(&p,sizeof(p),1,entrada);
// void niveling(struct persona p, int i);
// grupoedad(struct persona p, int j);
// femasc(struct persona p, int k);
i = niveling(p);
j = grupoedad(p);
k = femasc(p);
printf("\n%d",i);
printf("\n%d",j);
printf("\n%d",k);
A[i][j][k].notas = A[i][j][k].notas + p.notas;
A[i][j][k].cont = A[i][j][k].cont;
if(p.exi = 'S') {
A[i][j][k].contex = A[i][j][k].contex + 1;
}
}
for(i = 0; i < 5; i++) { //TOTALIZO HOMBRES Y MUJERES
for(j = 0; j < 6; j++) {
A[i][j][3].notas = A[i][j][3].notas + A[i][j][2].notas;
A[i][j][3].cont = A[i][j][3].cont + A[i][j][2].cont;
A[i][j][3].contex = A[i][j][3].contex + A[i][j][2].contex;
}
}
for(j = 0; j < 6; j++) {
for(i = 0; i < 5; i++) {
cantidadM = cantidadM + A[i][j][1].cont;
califM = califM + A[i][j][1].notas;
}
}
prom_m = califM / cantidadM; //PROMEDIO DE CALIFICACIONES DE LOS HOMBRES
for(j = 0; j < 6; j++) {
for(i = 0; i < 5; i++) {
cantidadF = cantidadF + A[i][j][2].cont;
califF = califF + A[i][j][2].notas;
}
}
prom_f = califF / cantidadM; //PROMEDIO DE CALIFICACIONES MUJERES
for(k = 0; k < 2; k++) {
for(i = 0; i < 5; i++) {
for(j = 0; j < 6; j++) {
A[6][j][k].cont = A[6][j][k].cont + A[i][j][k].cont;
A[6][j][k].contex = A[6][j][k].contex + A[i][j][k].cont;
A[6][j][k].notas = A[6][j][k].notas + A[i][j][k].notas;
}
}
}
for(j = 0; j < 6; j++) {
A[6][j][3].cont = A[6][j][1].cont + A[6][j][2].cont;
A[6][j][3].cont = A[6][j][1].contex + A[6][j][2].contex;
A[6][j][3].notas = A[6][j][1].notas + A[6][j][2].notas;
}
resmay = A[6][1][3].contex;
for(j = 0; j < 6; j++) {
if(A[6][j][3].contex > resmay) {
resmay = A[6][j][3].contex;
jex = j;
}
}
for(j = 0; j < 6; j++) {
for(k = 0; k < 3; k++) {
A[7][j][k].notas = A[6][j][k].notas / A[6][j][k].cont;
}
}
resmen = A[7][1][3].notas;
resmay = A[7][1][3].notas;
for(j = 0; j < 6; j++) {
if(A[7][j][3].notas > resmay) {
resmay = A[7][j][3].notas;
jmay = j;
}
else {
if(A[7][j][3].notas < resmen) {
resmen = A[7][j][3].notas;
jmen = j;
}
}
}
etario(jmay, grupoed);
printf("\nEl rango etario con mayor calificacion en promedio fue el comprendido entre: %s%s", grupoed, " años");
etario(jmen, grupoed);
printf("\nEl rango etario con menor calificacion en promedio fue el comprendido entre: %s%s", grupoed, " años");
printf("\nEl promedio de calificaciones en femeninos fue: %f", prom_f);
printf("\nEl promedio de calificaciones en masculinos fue: %f", prom_m);
etario(jex, grupoed);
printf("\nEl rango etario con mayor interes en rendir examenes internacionales es el comprendido entre: %s", grupoed, "años");
fclose(entrada);
system("pause");
return 0;
}
`
enter image description here
there we can see that the values of i, j and k are out of the array defined range, so obviusly it breaks the code...
Just in case i will explain how the file was made, it was generated by another program that use rand function to generate random data about people in a certain range, also it has a print just to have control of the values that the structs are taking:
`
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
struct persona {
int edad; //EDAD DE 12-65//
int notas; //NOTAS DE 0-10//
char sexo; //SEXO 1=MASCULINO Y 2=FEMENINO//
char exi; //EXI 1=SI 2=NO
};
void generacion()
{
FILE *entrada;
entrada=fopen("datospersonas.txt","ab");
if (entrada == NULL){
exit(1);
}
fclose(entrada);
}
int main()
{
int s;
int exi;
generacion();
persona p;
FILE* entrada;
entrada=fopen("datospersonas.txt","ab");
srand(time(NULL));
for (size_t i=0;i<650; i++)
{
p.edad =(rand() %54)+12;
p.notas =(rand() %10)+1;
s=(rand() %2)+1;
if(s == 1){
p.sexo='M';
}
else{
p.sexo='F';
}
exi=(rand() %2)+1;
if(exi == 1){
p.exi='S';
}
else{
p.exi='N';
}
fwrite(&p, sizeof(struct persona),1,entrada);
printf("edad: %d\n",p.edad);
printf("nota: %d\n",p.notas);
printf("sexo: %c\n",p.sexo);
printf("esta interesado en rendir examenes internacionales: %c\n",p.exi);
}
fclose(entrada);
return 0;
}
`
I have tried doing a file manually, like charging the data by myself to see if the file its not the problem.

im having problems with realloc "realloc():invalid old size"

hi i've been doing some coding with dynamic memory and double pointers, and work fine in the first part, but when it starts executing the second part(the second double pointer) which is exactly coded as the first one it stops working
main.c.
int main(int cant,char **argv)
{
int troden;
if(cant != 3)
{
printf("papu ta mal /n");
}
else
{
troden = archivOrden(*(argv + 1),*(argv + 2));
}
return 0;
}
function.c
#include "funciones.h"
int archivOrden(char *fileName1,char *fileName2)
{
FILE *arch1 =NULL,*arch2 = NULL;
char **vec1 = NULL;
char **vec2 = NULL;
char **aux = NULL;
int ret = 0;
int i = 0, j = 0, x = 0;
int a;
arch1=fopen(fileName1,"r");
arch2=fopen(fileName2,"r");
if(arch1 == NULL || arch2 == NULL)
{
printf("error al querer crear arch \n");
}
else
{
vec1 = (char**)malloc(sizeof(char)*1);
vec2 = (char**)malloc(sizeof(char)*1);
if(vec1 == NULL || vec2 == NULL) ret = -1;
if(ret == 0)
{
*vec1 = (char*)malloc(sizeof(char)*1);
*vec2 = (char*)malloc(sizeof(char)*1);
if(*vec1 == NULL || *vec2 == NULL) ret = -1;
if(ret == 0)
{
while(!feof(arch1))
{
*(vec1+j) = realloc(*(vec1+j),sizeof(char)*(1+i));
fread((*(vec1+j)+i),sizeof(char),1,arch1);
if(*(*(vec1+j)+i) =='\n')
{
*(*(vec1+j)+i) = '\0';
printf("%s \n",*(vec1+j));
j++;
i = 0;
vec1 = realloc(vec1,sizeof(char)*(1+j));
*(vec1+j) = (char*)malloc(sizeof(char)*(1+i));
}
else i++;
}
*(vec1+j) = realloc(*(vec1+j),sizeof(char)*(1+i));
*(*(vec1+j)+i) = '\0';
i = 0;
while(!feof(arch2))
{
*(vec2+x) = realloc(*(vec2+x),sizeof(char)*(1+i));
fread((*(vec2+x)+i),sizeof(char),1,arch2);
if(*(*(vec2+x)+i) =='\n')
{
//pongo un \0 en el final de la linea
*(*(vec2+x)+i) = '\0';
printf("%s \n",*(vec2+x));
// paso a la siguiente linea
x++;
i = 0;
vec2 = (char**)realloc(vec2,sizeof(char)*(1+x));
*(vec2+x) = (char*)malloc(sizeof(char)*(1+i));
}
else i++;
}
*(vec2+x) = realloc(*(vec2+x),sizeof(char)*(1+i));
*(*(vec2+x)+i) = '\0';
printf("paso por aca \n");
for(a = 0;a<j;a++)
{
printf("%d: %s /n",a,*(vec1+j));
}
for(a = 0;a<x;a++)
{
printf("%d: %s \n",a,*(vec2+a));
}
}
}
}
printf("finalice \n");
fclose(arch1);
fclose(arch2);
for(a = 0;a<j;a++)
{
free(*(vec1+a));
}
for(a = 0;a<x;a++)
{
free(*(vec2+a));
}
free(vec1);
free(vec2);
return ret;
}
it breaks when it starts the second while and reaches the first '/n',
but i cant understand because i do the exact same in the first while and works perfectly fine.

Why am I getting a 'public_stream ! = nullptr' error on execution, even though I have successfully used 'fopen_s' to read a file?

I am writing a scheduling algorithm while studying the Operating System.
And 'fopen_s' was used to receive information about the process from a 'txt' file.
First, I checked the function's output with 'errno_t', and it was normal with '0'.
However, if I try to execute it, an error such as an image appears and cannot proceed. Where did the error occur?
This code was written in Visual Studio 2017 using the c language.
This is 'process.txt'. (All are integers.)
1 1 0 10 3
1 2 0 1 1
1 3 0 2 4
1 4 0 5 2
2 5 0 5 2
2 6 0 4 3
2 7 0 1 2
2 8 0 7 1
3 9 0 5 2
3 10 0 4 3
3 11 0 1 4
3 12 0 6 1
This is the core code that causes the error.
int main()
{
sem_init(&semaphore, 0, 1);
q1 = (Process *)malloc(sizeof(Process) * 100);
q2 = (Process *)malloc(sizeof(Process) * 100);
q3 = (Process *)malloc(sizeof(Process) * 100);
FILE *fpp = NULL;
errno_t err = fopen_s(&fpp, "sample.txt", "r");
if (fpp = NULL)
{
printf("OPEN ERROR\n");
return 0;
}
while (!feof(fpp))
{
fscanf_s(fpp, "%d %d %d %d %d",
&class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);
if (class_num == 1)
{
q1[i_q1].id = sub_id;
q1[i_q1].arrive_time = sub_arrive_time;
q1[i_q1].burst = sub_burst;
q1[i_q1].priority = sub_priority;
i_q1++;
}
else if (class_num = 2)
{
q2[i_q2].id = sub_id;
q2[i_q2].arrive_time = sub_arrive_time;
q2[i_q2].burst = sub_burst;
q2[i_q2].priority = sub_priority;
i_q2++;
}
else if (class_num = 3)
{
q3[i_q3].id = sub_id;
q3[i_q3].arrive_time = sub_arrive_time;
q3[i_q3].burst = sub_burst;
q3[i_q3].priority = sub_priority;
i_q3++;
}
p_count++;
}//초기화 완료
pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
pthread_join(thread[idx], NULL);
fclose(fpp);
free(q1);
free(q2);
free(q3);
system("pause");
return 0;
}
This is the full code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <semaphore.h>
#define TRUE 1
#define FALSE 0
typedef struct _process {
int id;
int arrive_time;
int waiting_time;
int return_time;
int turnaround_time;
int response_time;
int burst;
int priority;
int completed;
}Process;
//쓰레드 동기화를 동기화를 위한 semaphore
sem_t semaphore;
int process_count = 0;
int p_count = 0;
int i_q1 = 0;
int i_q2 = 0;
int i_q3 = 0;
int class_num;
int sub_id;
int sub_arrive_time;
int sub_burst;
int sub_priority;
Process *q1;
Process *q2;
Process *q3;
int idx = 0;
pthread_t thread[5];
int time_quantum = 2;
//프로세스 초기화
void p_init(Process p[], int length)
{
int i;
for (i = 0; i < length; i++)
{
p[i].waiting_time = 0;
p[i].return_time = 0;
p[i].response_time = 0;
p[i].completed = FALSE;
}
}
int all_completed(Process *p1, Process *p2, Process *p3, int q1_len, int q2_len, int q3_len)
{
int i;
for (i = 0; i < q1_len; i++)
{
if (p1[i].completed == FALSE)
return FALSE;
}
for (i = 0; i < q2_len; i++)
{
if (p2[i].completed == FALSE)
return FALSE;
}
for (i = 0; i < q2_len; i++)
{
if (p3[i].completed == FALSE)
return FALSE;
}
return TRUE;
}
void print_table(Process p[], int n)
{
int i;
// 반복문에서 사용할 변수 선언
puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
puts("\t| PID | Burst Time | Arrive Time | Priority | Return Time | Response Time | Waiting Time | Turnaround Time |");
puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
/* 프로세스 갯수만큼 반복하며 포맷을 맞추어 출력 */
for (i = 0; i < n; i++)
{
printf("\t| %3d | %3d | %3d | %3d | %3d | %3d | %3d | %3d |\n",
p[i].id, p[i].burst, p[i].arrive_time, p[i].priority, p[i].return_time, p[i].response_time, p[i].waiting_time, p[i].turnaround_time);
puts("\t+-----+------------+-------------+----------+-------------+-----------------+--------------+-----------------+");
}
puts("\n");
}
// 반환 시간을 비교하는 함수
int compare_by_return_time(const void *a, const void *b)
{
Process *pA = (Process *)a;
Process *pB = (Process *)b;
/* pA의 반환 시간이 작을 경우 */
if (pA->return_time < pB->return_time)
return -1;
/* ptA의 반환 시간이 클 경우 */
else if (pA->return_time > pB->return_time)
return 1;
/* 반환 시간이 같을 경우 -> 존재 X */
else
return 0;
}
// 반환 시간을 퀵 소트 기반으로 정렬한다.
void quick_sort_by_return_time(Process p[], int len)
{
qsort(p, len, sizeof(Process), compare_by_return_time);
}
// 우선 순위를 비교하는 함수
int compare_by_priority(Process *a, Process *b)
{
Process *pA = (Process *)a;
Process *pB = (Process *)b;
if (a->priority == b->priority) {
if (a->burst != b->burst) {
if (a->burst < b->burst)
return -1;
else
return 1;
}
else
return 0;
}
else {
if (a->priority < b->priority)
return -1;
else if (a->priority > b->priority)
return 1;
}
}
void quick_sort_by_priority_time()
{
qsort(q1, i_q1, sizeof(Process), compare_by_priority);
}
void gantt_chart(Process p[], int len)
{
int i, j; // 반복문에 사용할 변수
printf("\t ");
for (i = 0; i < len; i++)
{
for (j = 0; j < p[i].burst; j++)
printf("--");
printf(" ");
}
printf("\n\t|");
for (i = 0; i < len; i++)
{
for (j = 0; j < p[i].burst - 1; j++)
printf(" ");
printf("%d", p[i].id);
for (j = 0; j < p[i].burst - 1; j++)
printf(" ");
printf("|");
}
printf("\n\t ");
for (i = 0; i < len; i++)
{
for (j = 0; j < p[i].burst; j++)
printf("--");
printf(" ");
}
printf("\n\t");
printf("0");
for (i = 0; i < len; i++)
{
for (j = 0; j < p[i].burst; j++)
printf(" ");
if (p[i].return_time > 9)
printf("\b");
printf("%d", p[i].return_time);
}
printf("\n");
}
//**************************************************//
// Q1 : Non-preemptive Priority Scheduling Algorithm
// 알고리즘 시간 계산 함수
void Cal_for_npps(Process p[], int len)
{
int i, j; // 반복문에 사용할 변수
int check; // 모든 프로세스 완료 여부 확인
int min; // Priority가 가장 높은 index 저장
int time = 0; // 현재 시간
p[0].return_time = p[0].burst;
p[0].turnaround_time = p[0].return_time - p[0].arrive_time;
p[0].response_time = 0;
p[0].completed = TRUE;
time = p[0].burst;
while (TRUE)//모든 프로세스 완료 시 종료
{
min = INT_MAX;
check = FALSE;
for (i = 1; i < len; i++)//Priority가 가장 높은 프로세스 탐색
{
if ((p[min].priority > p[i].priority) && (p[i].completed == FALSE))
{//현재 Priority보다 작은 Priority 가졌지만 실행되지 않았다면 갱신
min = i;
check = TRUE;
}
}
if (check == FALSE)//모든 프로세스 완료 시 반복문 탈출
break;
p[min].response_time = time - p[min].arrive_time;
p[min].return_time = time + p[min].burst;
p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
p[min].waiting_time = time - p[min].arrive_time;
p[min].completed = TRUE;
time += p[min].burst;
}
}
void *NPPS(void *arg)
{
int i; // 반복문에 사용할 변수
int total_waiting_time = 0;
int total_turnaround_time = 0;
int total_response_time = 0;
p_init(q1, i_q1);
quick_sort_by_priority_time();
Cal_for_npps(q1, i_q1);
for (i = 0; i < i_q1; i++)
{
total_waiting_time += q1[i].waiting_time;
total_turnaround_time += q1[i].turnaround_time;
total_response_time += q1[i].response_time;
}
quick_sort_by_return_time(q1, i_q1);
printf("\tNon-preemptive Priority Scheduling Algorithm\n\n");
gantt_chart(q1, i_q1);
printf("\n\tAverage Waiting Time : %-2.2lf\n", (double)total_waiting_time / (double)i_q1);
printf("\tAverage Turnaround Time : %-2.2lf\n", (double)total_turnaround_time / (double)i_q1);
printf("\tAverage Response Time : %-2.2lf\n\n", (double)total_response_time / (double)i_q1);
print_table(q1, i_q1);
}
//**************************************************//
// Q2 : HRN(Highest Response-Ratio Next)
void *HRN(void *arg)
{
int i, j; // 반복문에 사용할 변수
int time, locate; // 현재 시간과 프로세스 위치
int total_burst_time = 0;
int total_waiting_time = 0;
int total_turnaround_time = 0;
int total_response_time = 0;
float hrr, temp; // 우선순위 저장
p_init(q2, i_q2);
for (i = 0; i < i_q2; i++)
{
total_burst_time += q2[i].burst;
}
for (time = q2[0].arrive_time; time < total_burst_time;)
{
hrr = -99999;
for (i = 0; i < i_q2; i++)// Priority가 가장 높은 프로세스 탐색
{
if (q2[i].completed != TRUE)
{
temp = (q2[i].burst + (time - q2[i].arrive_time)) / q2[i].burst;
if (hrr < temp)//우선순위 갱신
{
hrr = temp;
locate = i;
}
}
}
time += q2[locate].burst;
q2[locate].waiting_time = time - q2[locate].arrive_time - q2[locate].burst;
q2[locate].turnaround_time = time - q2[locate].arrive_time;
q2[locate].return_time = q2[locate].turnaround_time + q2[locate].arrive_time;
q2[locate].response_time = q2[locate].waiting_time;
q2[locate].completed = TRUE;
total_waiting_time += q2[locate].waiting_time;
total_turnaround_time += q2[locate].turnaround_time;
total_response_time += q2[locate].response_time;
}
quick_sort_by_return_time(q2, i_q2);
printf("\tHighest Response Ratio Next Scheduling Algorithm\n\n");
gantt_chart(q2, i_q2);
printf("\n\tAverage Waiting Time : %-2.2lf\n", (double)total_waiting_time / (double)i_q2);
printf("\tAverage Turnaround Time : %-2.2lf\n", (double)total_turnaround_time / (double)i_q2);
printf("\tAverage Response Time : %-2.2lf\n\n", (double)total_response_time / (double)i_q2);
print_table(q2, i_q2);
}
void cal_for_sjf(Process *p, int len)
{
int i, j; // 반복문에 사용할 변수
int cur_time = 0; // 현재 시간
int min = 0; // 최소 시간을 갖는 인덱스 저장
p[0].completed = TRUE;
p[0].return_time = p[0].burst;
p[0].turnaround_time = p[0].burst - p[0].arrive_time;
p[0].waiting_time = 0;
cur_time = p[0].burst;
for (i = 1; i < len; i++)
{
for (j = 1; j < len; j++)
{
if (p[j].completed == TRUE)
continue;
else
{
min = j;
break;
}
}
for (j = 1; j < len; j++)
{
if ((p[j].completed == FALSE) && (p[j].burst < p[min].burst))
{
min = j;
}
}
p[min].waiting_time = cur_time - p[min].arrive_time;
p[min].completed = TRUE;
cur_time += p[min].burst;
p[min].return_time = cur_time;
p[min].turnaround_time = p[min].return_time - p[min].arrive_time;
}
}
void *SJF(void *arg)
{
int i;
int total_waiting_time = 0;
int total_turnaround_time = 0;
int total_response_time = 0;
p_init(q3, i_q3);
cal_for_sjf(q3, i_q3);
for (i = 0; i < i_q3; i++)
{
q3[i].return_time = q3[i].turnaround_time + q3[i].arrive_time;
q3[i].response_time = q3[i].waiting_time;
total_waiting_time += q3[i].waiting_time;
total_turnaround_time += q3[i].turnaround_time;
total_response_time += q3[i].response_time;
}
printf("\tSJF Scheduling Algorithms\n\n");
quick_sort_by_return_time(q3, i_q3);
gantt_chart(q3, i_q3);
printf("\n\tAverage Waiting Time : %-2.2lf\n", (double)total_waiting_time / (double)i_q3);
printf("\tAverage Turnaround Time : %-2.2lf\n", (double)total_turnaround_time / (double)i_q3);
printf("\tAverage Response Time : %-2.2lf\n\n", (double)total_response_time / (double)i_q3);
print_table(q3, i_q3);
}
void *MLQS(void *arg)
{
idx++;
while (all_completed(q1, q2, q3, i_q1, i_q2, i_q3)) {
sem_wait(&semaphore);
if (idx == 1) {
pthread_create(&thread[idx], NULL, NPPS, NULL);
pthread_join(thread[idx], NULL);
}
else if (idx == 2) {
pthread_create(&thread[idx], NULL, HRN, NULL);
pthread_join(thread[idx], NULL);
}
else if (idx == 3) {
pthread_create(&thread[idx], NULL, SJF, NULL);
pthread_join(thread[idx], NULL);
}
idx++;
sem_post(&semaphore);
if (idx > 3)
idx = 1;
}
}
int main()
{
sem_init(&semaphore, 0, 1);
q1 = (Process *)malloc(sizeof(Process) * 100);
q2 = (Process *)malloc(sizeof(Process) * 100);
q3 = (Process *)malloc(sizeof(Process) * 100);
FILE *fpp = NULL;
errno_t err = fopen_s(&fpp, "sample.txt", "r");
if (fpp = NULL)
{
printf("OPEN ERROR\n");
return 0;
}
while (!feof(fpp))
{
fscanf_s(fpp, "%d %d %d %d %d",
&class_num, &sub_id, &sub_arrive_time, &sub_burst, &sub_priority);
if (class_num == 1)
{
q1[i_q1].id = sub_id;
q1[i_q1].arrive_time = sub_arrive_time;
q1[i_q1].burst = sub_burst;
q1[i_q1].priority = sub_priority;
i_q1++;
}
else if (class_num = 2)
{
q2[i_q2].id = sub_id;
q2[i_q2].arrive_time = sub_arrive_time;
q2[i_q2].burst = sub_burst;
q2[i_q2].priority = sub_priority;
i_q2++;
}
else if (class_num = 3)
{
q3[i_q3].id = sub_id;
q3[i_q3].arrive_time = sub_arrive_time;
q3[i_q3].burst = sub_burst;
q3[i_q3].priority = sub_priority;
i_q3++;
}
p_count++;
}//초기화 완료
pthread_create(&thread[idx], NULL, MLQS, NULL);//별도의 함수 만들어서 넣기
pthread_join(thread[idx], NULL);
fclose(fpp);
free(q1);
free(q2);
free(q3);
system("pause");
return 0;
}
Beside all the issues mentioned in the comments:
if (fpp = NULL)
assigns NULL to ffp instead of comparing it (and the condition is always false). You mean
if (fpp == NULL)

Adjacency list and struct Dijkstra

I must create a Dijkstra algorithm program using an adjacency list. My teacher give me this struct.
But I have this error :
note: expected 'struct maillon **' but argument is of type 'LISTE'
void insere(int som_a, int som_b, int poids, LISTE Adj[]){
Where the argument nom is vertices, poids is weight, som_a and som_b are vertices.
function void insere : insert (som_b, poids) At the top of the adjacency list Adj[som_a]
typedef struct maillon{
struct maillon *suiv;
int nom;
int poids;
} MAILLON, *LISTE;
void insere(int som_a, int som_b, int poids, LISTE Adj[]) {
LISTE prem = malloc(sizeof(LISTE));
prem->nom = som_b;
prem->poids = poids;
prem->suiv = Adj[som_a];
Adj[som_a] = prem;
}
void dijsktra(int s, GRAPHE G) {
int i, j, dist[NB_SOM_MAX], INT_MAX = 0, pred[NB_SOM_MAX], min, nb = 0, nbmin = 0;
LISTE S,F = G.Adj;
for(i = 0; i < G.nbSommets; i++) {
dist[i] = INT_MAX;
pred[i] = NULL;
}
dist[0] = 0;
S = NULL;
while(F != NULL){
min = G.Adj[0]->poids;
for(i = 1; i < G.nbSommets; i++) {
if(min > G.Adj[i]->poids) {
min = G.Adj[i]->poids;
nbmin = i;
}
}
insere(nb, nbmin, min, S);
nb++;
if(nbmin == 0){
F = F->suiv;
}
else{ // F[nbmin-1]->suiv = F[nbmin + 1];
F[nbmin - 1] = F[nbmin + 1];
}
for(i = G.Adj[nbmin]->nom; i < G.nbSommets; i++){
if(dist[i] > dist[nbmin] + G.Adj[nbmin]->poids){
dist[i] = dist[nbmin] + G.Adj[nbmin]->poids;
pred[i] = nbmin;
}
}
}
for(i = 0; i < G.nbSommets; i++){
printf("Chemin optimal de %d à %d : ", i, s);
printf("%d-", i);
j = i;
while(pred[j] != s || pred[j] != NULL){
printf("%d-", pred[j]);
j = pred[j];
}
printf("\n");
}
}

Resources