Game of Life .exe strange output - c

I wrote a C code for a Game of Life simulation. My program works perfectly fine for case 1 which is my random array. But it doesn't work when I try to load an array out of a .txt file. I mean it gives me an output but it doesn't output an array with '*' or ' ' it gives me this:
Does someone know what my mistake is?
Here´s my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
#define ED 25
#define ZD 25
// - FUNCTIONS
void print_matr(char matr[ED][ZD], int n, int m);
void create_matr(char matr[ED][ZD], int n, int m, int *alz, int prozent);
void check_neighbours(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz);
void ausfuehren(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz);
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz);
int Menu(char *text, int anz, char *prompt);
int check_rules(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int lx, int ly, int alz);
int Einlesen(char *prompt, int min, int max, int versuche);
// -MAIN-
int main() {
const int n = ED; const int m = ZD; //1.Dim/2.Dim
char matr[ED][ZD];
char lager[ED][ZD];
int alz; //Anzahl lebender Zellen
int prozent;
switch (Menu("\n1 - random\n2 - load array 1\n3 - load array 2\n4 - load array 3\n\n0 - exit", 5, "\n >>>> ")) {
case 0: exit(0); break;
case 1:
prozent = Einlesen("Percentage? ", 0, 100, 5);
create_matr(matr, n, m, &alz, prozent);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz);
break;
case 2:
load_matr(matr, n, m, 1,&alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz); break;
case 3:
load_matr(matr, n, m, 2,&alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz); break;
case 4:
load_matr(matr, n, m, 3, &alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz);
break;
}
return 0;
}
// -PRINT
void print_matr(char matr[ED][ZD], int n, int m) {
for (int lx = 0; lx < n; lx++) {
for (int ly = 0; ly < m; ly++) {
printf(" %c", matr[lx][ly]);
}
printf("\n");
}
printf("\n\n");
}
int Einlesen(char *prompt, int min, int max, int versuche) {
int zahl;
fflush(stdin);
if (!versuche) {
exit(0);
}
printf(prompt);
if (!scanf("%d", &zahl)) {
printf(" *** Bitte Zahl eingeben! ***\n");
return Einlesen(prompt, min, max, versuche - 1);
}
if ((zahl<min) || (zahl>max)) {
printf(" *** [%d,%d]! ***\n", min, max);
return Einlesen(prompt, min, max, versuche - 1);
}
return zahl;
}
int Menu(char *text, int anz, char *prompt) {
printf(text);
return Einlesen(prompt, 0, anz, 5);
}
void create_matr(char matr[ED][ZD], int n, int m, int *alz, int prozent) {
for (int ln = 0; ln < n; ln++) {
for (int lm = 0; lm < m; lm++) {
if (rand()%100 <= prozent) {
matr[ln][lm] = '*';
(*alz)++;
}
else { matr[ln][lm] = ' ';}
}
}
}
int check_rules(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int lx, int ly, int l_anzlz) {
//Rule 1
if (matr[lx][ly] == '*') {
if ((l_anzlz == 0) || (l_anzlz == 1) || (l_anzlz > 3)) {
lager[lx][ly] = ' ';
}
//Rule 2
else if ((l_anzlz == 2) || (l_anzlz == 3)) {
lager[lx][ly] = '*';
}
}
//Rule 3
else if (matr[lx][ly] == ' ') {
if (l_anzlz == 3) {
lager[lx][ly] = '*';
}
else lager[lx][ly] = ' ';
}
return 1;
}
void check_neighbours(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz) {
int counteq = 0;
int l_anzlz;
(*alz)=0;
for(int lx = 0; lx < n; lx++) {
for(int ly = 0; ly < m; ly++) {
l_anzlz = 0;
for(int la = -1; la <= 1; la++) {
for(int lb = -1; lb <= 1; lb++) {
if((la==0)&&(lb==0)) continue;
if((lx==0)&&(la==-1)) continue;
if((lx==n-1)&&(la==1)) continue;
if((ly==0)&&(lb==-1)) continue;
if((ly==m-1)&&(lb==1)) continue;
if (matr[lx + la][ly + lb] == '*') {
l_anzlz++;
}
}
}
check_rules(matr, n, m, lager, lx, ly, l_anzlz);
}
}
//printf("lager\n");
//print_matr(lager, n, m);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++) {
if (matr[i][j] == lager[i][j]) {
counteq++;
}
matr[i][j] = lager[i][j];
if (matr[i][j] == '*') (*alz)++;
}
}
if (counteq == (n*m)) (*alz)=0;
}
// -EXECUTE
void ausfuehren(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz) {
char eing;
int fors;
fors = Einlesen(" [0] or [1]?\n", 0, 1, 2);
if(fors==1) printf(" 'q' to end \n");
while ((*alz) > 0) {
check_neighbours(matr, n, m, lager, alz); /
print_matr(matr, n, m);
if (fors == 0) {
Sleep(300);
}
else if (fors == 1) {
fflush(stdin);
scanf("%c", &eing);
if(eing=='q') break;
}
}
}
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz) {
FILE *fp;
char c[4];
(*alz)=0;
if (filenr == 1) {
fp = fopen("matrix1.txt", "rt");
}
else if (filenr == 2) {
fp = fopen("matrix2.txt", "rt");
}
else if (filenr == 3) {
fp = fopen("matrix3.txt", "rt");
}
if(fp==0){
printf("Couldnt open File!");
exit(-1);
}
if(fgets(c, 5, fp)==NULL){
printf("Error\n");
exit(-1);
}
n=(int)(*c);
if(fgets(c, 5, fp)==NULL){
printf("Error\n");
exit(-1);
}
m=(int)(*c);
for (int lx = 0; lx < n; lx++) {
for (int ly = 0; ly < m; ly++) {
int star = fgetc(fp);
if (star == 42) { //42=* | ASCII
matr[lx][ly] = '*';
(*alz)++;
}
else if (star == 32) { //32= | ASCII
matr[lx][ly] = ' ';
}
else if (star == 10) { //10=\n | ASCII
lx--; ly = m - 1;
}
else break; //EOF
}
}
fclose(fp);
}
Would appreciate any help!
Thanks!

Your problem is into the load_matr function:
This is a possible solution, that make it works when the input file is properly formatted (it is not a solution fault tolerant), and many bad things, but it works.
void clear_matr(char matr[ED][ZD])
{
for (int row = 0; row < ED; row++)
for (int col = 0; col < ZD; col++)
matr[row][col] = ' ';
}
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz) {
FILE *fp;
char c[16];
(*alz)=0;
memset(c, 0, sizeof(c));
if (filenr == 1) {
fp = fopen("matrix1.txt", "rt");
}
else if (filenr == 2) {
fp = fopen("matrix2.txt", "rt");
}
else if (filenr == 3) {
fp = fopen("matrix3.txt", "rt");
}
if (fp == 0) {
printf("Couldnt open File!");
exit(-1);
}
if (fgets(c, 5, fp) == NULL) {
printf("Error\n");
exit(-1);
}
n = atoi(c);
if (fgets(c, 5, fp) == NULL) {
printf("Error\n");
exit(-1);
}
m = atoi(c);
clear_matr(matr);
for (int ly = 0; ly < m; ly++) {
for (int lx = 0; lx < n; lx++) {
int star = fgetc(fp);
if (star == '\n')
star = fgetc(fp);
if (star == 42) { //42=* | ASCII
matr[ly][lx] = '*';
(*alz)++;
}
else if (star == 32) { //32= | ASCII
matr[ly][lx] = ' ';
}
else break; //EOF
}
}
fclose(fp);
}

Related

I am having trouble making a function that will open a file

void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n);
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n)
{
f= fopen( "TIMES.txt", "wb");
if((f=fopen("TIMES.txt", "wb"))==NULL) {
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f,"Array size: %d\n================\n ",n);
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<7;j++)
{
fwrite(arrTypeLabels[i] + j, sizeof (char), sizeof (char), f);
}
}
for(i=0;i<4;i++)
{
for(j=0;j<11;j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j==9 && i==0)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[0][df]);
}
if (j==9 && i==1)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[1][df]);
}
if (j==5 && i==2)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[2][df]);
}
if (j==5 && i==3)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[3][df]);
}
}
}
fclose(f);
}
//This is how i call it inside the main
writeResultsToFile(FILE *f,arrTypeLabels[3][7],sortNames[4][11],times[4][3],n);
the code inside it is right i tested it without the funtion, it works , i just dont know how to call it as a funtion if anybody can help.
Expected expression before FILE, and conflicted type errors..............................................
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char
sortNames[4][11], float times[4][3], int n);
int main(int argc, char *argv[])
{
int n=10;
char arrTypeLabels[3][7]= {"Random", "ASC", "DESC"},sortNames[4]
[11]={"Selection", "Insertion", "Shell", "Quick"};
FILE *f;
float times[4][3];
writeResultsToFile(f, arrTypeLabels, sortNames, times, n);
return 0;
}
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char
sortNames[4][11], float times[4][3], int n)
{
f= fopen( "TIMES.txt", "wb");
if((f=fopen("TIMES.txt", "wb"))==NULL) {
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f,"Array size: %d\n================\n ",n);
int i,j;
for(i=0;i<3;i++)
{
if(i==2){
fprintf(f," %s ",arrTypeLabels[i]);
}
else{
fprintf(f,"%s ",arrTypeLabels[i]);
}
}
for(i=0;i<4;i++)
{
fprintf(f,"\n");
for(j=0;j<11;j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j==9 && i==0)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[0][df]);
}
if (j==9 && i==1)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[1][df]);
}
if (j==5 && i==2)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[2][df]);
}
if (j==5 && i==3)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[3][df]);
}
}
}
fclose(f);
}
#include <stdlib.h>
#include <wchar.h>
#include <stdio.h>
int writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n);
int writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n)
{
f = fopen("TIMES.txt", "wb");
if ((f = fopen("TIMES.txt", "wb")) == NULL)
{
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f, "Array size: %d\n================\n ", n);
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 7; j++)
{
fwrite(arrTypeLabels[i] + j, sizeof (char), sizeof (char), f);
}
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 11; j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j == 9 && i == 0)
{
int df;
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[0][df]);
}
if (j == 9 && i == 1)
{
int df;
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[1][df]);
}
if (j == 5 && i == 2)
{
int df;
fprintf(f, " ");
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[2][df]);
}
if (j == 5 && i == 3)
{
int df;
fprintf(f, " ");
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[3][df]);
}
}
}
fclose(f);
}
int main(void)
{
//assign theses variables before calling your function
char arrTypeLabels[3][7];
char sortNames[4][11];
float times[4][3];
int n;
//--------------------------
FILE * f; //no need to assign this variable
writeResultsToFile(f, arrTypeLabels, sortNames, times, n); //call your function like that
return 0;
}

Why is does the file become NULL?

I'm new on the subject of data structures so forgive me if Im asking a stupid question, I've been trying to figure this out myself but got nowhere.
These are the functions I'm working on and I think I initialized the file properly. However I couldn't understand why the function GetString prints an infinite loop of spaces. I have another function that exported some data on the said file. When i deleted the ImportListOfCompanyData function everything seems in order and the file is exported as it should be. However when ImportListOfCompanyData is there, the file is NULL.
void char * GetString(FILE *fp)
{
char c;
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
void ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c;
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
GetString(fp);
fclose(fp);
}
Someone asked for the complete code: It's bit long sorry!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 100
struct Department
{
char DepName[MAXNUM];
int NuEmp;
double Budget;
int dflag;
};
typedef struct Department DEP;
struct CompanyType
{
char CompName[MAXNUM];
char OwnerName[MAXNUM];
int Year;
double StockPrice;
int flag;
DEP Dep[MAXNUM];
};
struct ImpDepartment
{
char IDepName[MAXNUM];
int INuEmp;
double IBudget;
int Idflag;
};
typedef struct ImpDepartment IDEP;
struct ImpCompanyType
{
char ICompName[MAXNUM];
char IOwnerName[MAXNUM];
int IYear;
double IStockPrice;
int Iflag;
IDEP IDep[MAXNUM];
};
void CreateCompany(struct CompanyType s[], char * cname, char * cowner, int year, double sprice, int i)
{
strcpy(s[i].CompName, cname);
strcpy(s[i].OwnerName, cowner);
s[i].Year = year;
s[i].StockPrice = sprice;
s[i].flag = 0;
}
int PrintCompany(struct CompanyType s[], int maxit1, int maxit2)
{
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
printf("%d. Company %s: \n\n", i + 1, s[i].CompName);
printf("****************\n");
printf("Owned by: %s\n", s[i].OwnerName);
printf("Establishment year: %d\n", s[i].Year);
printf("Stock price: %.2lf\n", s[i].StockPrice);
printf("****************\n\n");
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
printf("****************\n");
printf("%d. Department %s: \n", j + 1, s[i].Dep[j].DepName);
printf("Number of employees: %d\n", s[i].Dep[j].NuEmp);
printf("Budget: %.2lf\n", s[i].Dep[j].Budget);
printf("****************\n\n");
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
}
int CompareName(char * str1, char * str2)
{
char *stra, *strb;
int result;
result = strcmp(str2, str1);
return result;
}
void DeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
s[i].flag = 1;
printf("Company %s was successfully deleted!\n", s[i].CompName);
}
else
printf("The input is wrong!");
}
void UnDeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 0)
{
printf("The Company %s wasn't deleted in the first place.\n\n", s[i].CompName);
}
else
{
s[i].flag = 0;
printf("Company %s was successfully undeleted!\n\n", s[i].CompName);
}
}
else
printf("The input is wrong!");
}
int SearchForCompany(struct CompanyType s[], char * cname, int maxit, int a)
{
int i = 0;
int check = 0;
int m = 0;
while(i <= maxit)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 1)
{
printf("The company ""%s"" doesn't exist\n\n", cname);
}
else
{
if(a == 1)
{
printf("The company %s was found!", s[i].CompName, s[i].CompName);
m = 1;
}
else
m = 1;
}
}
else
printf("The company ""%s"" doesn't exist\n\n", cname);
if (m == 1)
return i;
else
return -1;
}
void AddDeparments(struct CompanyType s[], char * cname, int maxit, int a, char * dname, int nem, double bud, int depno)
{
int n;
n = SearchForCompany(s,cname, maxit, a);
if(maxit == -1)
return -1;
strcpy(s[n].Dep[depno].DepName, dname);
s[n].Dep[depno].NuEmp = nem;
s[n].Dep[depno].Budget = bud;
s[n].Dep[depno].dflag = 0;
printf("The department %s was created in the %s company\n",s[n].Dep[depno].DepName, s[n].CompName);
}
int SearchForDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
printf("The department ""%s"" doesn't exist.\n\n", dname);
}
else
(*succ) = 1;
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
int SearchForDelDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
(*succ) = 1;
}
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
void DeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
{
s[i].Dep[j].dflag = 1;
printf("The department %s was deleted from the %s company\n", dname, s[i].CompName);
}
}
void UnDeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDelDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
s[i].Dep[j].dflag = 0;
if(s[i].Dep[j].dflag == 0)
printf("The department %s was undeleted\n", dname);
}
ExportListOfCompanyData(struct CompanyType s[], int maxit1, int maxit2, char * FileName)
{
FILE *fp;
fp = fopen(FileName, "w");
if (fp==NULL)
{
printf("Error creating the file \n");
return -1;
}
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].CompName);
fprintf(fp,"%s\n", s[i].OwnerName);
fprintf(fp,"%d\n", s[i].Year);
fprintf(fp,"%.2lf\n\n", s[i].StockPrice);
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].Dep[j].DepName);
fprintf(fp,"%d\n", s[i].Dep[j].NuEmp);
fprintf(fp,"%.2lf\n\n", s[i].Dep[j].Budget);
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
fclose(fp);
}
char * GetString(FILE *fp)
{
char * str; char c;
str = (char *)malloc(sizeof(char)* MAXNUM);
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c, *str;
str = (char *)malloc(sizeof(char)* MAXNUM);
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
int i = 0, j = 0, n;
GetString(fp);
fclose(fp);
return 0;
}
int main()
{
struct CompanyType CompanyList[MAXNUM];
CreateCompany(CompanyList, "alara inc", "alara", 2020, 6969, 0);
CreateCompany(CompanyList, "Shah inc", "shah", 2020, 3245, 1);
DeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
UnDeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
SearchForCompany(CompanyList, "alara inc", 1, 1);
AddDeparments(CompanyList, "alara inc", 1, 0, "computer", 20, 300, 0);
AddDeparments(CompanyList, "Shah inc", 1, 0, "chemistry", 30, 450, 0);
DeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
UnDeleteDepartments(CompanyList, 0, 1, 0, "computer");
PrintCompany(CompanyList, 1, 1);
UnDeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
ExportListOfCompanyData(CompanyList, 1, 1, "Data.txt");
ImportListOfCompanyData("Data.txt", CompanyList, 1, 1);
PrintCompany(CompanyList, 1, 1);
return 0;
}```
It was a really easy solution. I replaced "w" and "r" with "a+"
I guess it was a stupid question, still learning!

Maze by recursive division not working - C

I'm having some trouble with my recursive division generated maze. I know there's something wrong about the recursion, but I just can't find a way to solve it.
I also know the code is really big and not optimized at all, but I'm working better on this issue later.
The red maze is what I'm generating and the purple one is what I'm trying to do:
What should I be doing to correct that?
Tnks.
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#define MAX 41
#define FUNDO 0
#define PAREDE 1
#define SAIDA 2
#define SOLUCAO 3
int num_aleat(int min, int max)
{
return rand()%(max-min+1)+min;
}
void paredes(int m[][MAX], int FINAL_i, int FINAL_j, int INICIO_i, int INICIO_j)
{
int i=0, j=0;
for(i=0; i<MAX; i++)
{
if (i!=FINAL_i && i!=INICIO_i)
m[i][j]=PAREDE;
}
i=0;
for(j=0; j<MAX; j++)
{
if (j!=INICIO_j)
m[i][j]=PAREDE;
else
m[i][j]=SAIDA;
}
j=0;
for(i=0; i<MAX; i++)
{
if (j!=FINAL_j && j!=INICIO_j)
m[i][j+MAX-1]=PAREDE;
}
i=0;
for(j=0; j<MAX; j++)
{
if (j!=FINAL_j)
m[i+MAX-1][j]=PAREDE;
else
m[i+MAX-1][j]=SAIDA;
}
j=0;
}
void pardede_gener(int m[][MAX], int min, int max, int x, int dir)
{
int i=0, passagem=0;
switch (dir)
{
case 1:
passagem=num_aleat(min, max);
printf("\nc\n");
for(i=min; i<=max; i++)
{
if(i!=passagem)
m[i][x]=PAREDE;
printf("\nd_%i_%i\n", i, x);
}
return;
break;
case 2:
passagem=num_aleat(min, max);
for(i=min; i<=max; i++)
{
if(i!=passagem)
m[x][i]=PAREDE;
}
return;
break;
}
return;
}
void div(int m[][MAX], int i, int j, int max_i, int max_j, int dir)
{
int parede_i=MAX, parede_j=MAX, flag=0;
if(dir==1)
{
while(1)
{
parede_j=num_aleat(j, max_j);
if (parede_j%2==0 && m[i+1][parede_j]==FUNDO && m[i+1][parede_j-1]!=PAREDE && m[i+1][parede_j+1]!=PAREDE || m[i+2][parede_j]!=PAREDE)
break;
else
break;
}
if(m[i+1][parede_j]!=PAREDE && m[i+1][parede_j-1]!=PAREDE && m[i+1][parede_j+1]!=PAREDE)
{
pardede_gener(m, i+1, max_i-1, parede_j, dir);
dir=2;
div(m, i, j, max_i, parede_j, dir);
div(m, i, parede_j, max_i, max_j, dir);
}
else
return;
}
else if(dir==2)
{
while(1)
{
parede_i=num_aleat(j, max_j);
if (parede_i%2==0 && m[parede_i][j+1]==FUNDO && m[parede_i-1][j+1]!=PAREDE && m[parede_i+1][j+1]!=PAREDE || m[parede_i][j+2]==PAREDE)
break;
else
break;
}
if(m[parede_i][j+1]!=PAREDE && m[parede_i-1][j+1]!=PAREDE && m[parede_i+1][j+1]!=PAREDE)
{
pardede_gener(m, j, max_j-1, parede_i-1, dir);
dir=1;
div(m, i, j, parede_i, max_j, dir);
div(m, parede_i, j, max_i, max_j, dir);
}
else
return;
}
}
bool resolve(int *m, int i, int j, int fi, int fj)
{
*(m + i*MAX + j)=SOLUCAO;
if(i==fi-1 && j==fj)
return true;
if (i+1<MAX && *(m + (i+1)*MAX + j)==FUNDO)
{
if(resolve(m, i+1, j, fi, fj))
return true;
}
if (i-1>=0 && *(m + (i-1)*MAX + j)==FUNDO)
{
if(resolve(m, i-1, j, fi, fj))
return true;
}
if (j+1<MAX && *(m + i*MAX + (j+1))==FUNDO)
{
if(resolve(m, i, j+1, fi, fj))
return true;
}
if (j-1>=0 && *(m + i*MAX + (j-1))==FUNDO)
{
if(resolve(m, i, j-1, fi, fj))
return true;
}
*(m + i*MAX + j)=FUNDO;
return false;
}
int main()
{
int lab[MAX][MAX];
int FINAL_i=0, FINAL_j=0, INICIO_i=0, INICIO_j=0, i=0, j=0;
srand(time(NULL));
FINAL_i=MAX-1;
while (INICIO_j%2==0 || FINAL_j%2==0)
{
INICIO_j=rand()%(MAX-2)+1;
FINAL_j=rand()%(MAX-2)+1;
}
zero(lab);
paredes(lab, FINAL_i, FINAL_j, INICIO_i, INICIO_j);
div(lab, 0, 0, MAX-1, MAX-1, 1);
// resolve(*lab, 1, INICIO_j, FINAL_i, FINAL_j);
return 0;
}

Can't free memory from 2D dynamical array

I am having problem with freeing my memory. I did this many times, and it was working fine. Now, it just stops working (no error, anything, just freeze).
How my code looks like:
void args(int argc, char** argv, int *n, int *m, int **matrix, char name[20])
{
int firstIter = TRUE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setName(name, argv[x]);
loadMatrix(*m, *n, second, *name);
opMatrix(*m, *n, matrix, second, &*matrix, op);
}
else
{
setName(name, argv[x]);
loadSizeMatrix(n, m, name);
matrix = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matrix[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
loadMatrix(*m, *n, matrix, *name);
firstIter = FALSE;
}
}
printMatrix(*m, *n, matrix);
for (int i = 0; i < *n; i++) {
free(second[i]);
}
free(second[0]); //doesnt work too, and yes, there are data
free(second);
}
second is being filled like this (loadMatrix):
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &second[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
How can I solve this error?
my full code
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <ctype.h> //tolower
#include <string.h>
#define TRUE 1
#define FALSE !TRUE
/* konstanty */
const enum {
MAX_DELKA_SOUBORU = 10000,
MAX_SOUBOR = 20
};
const enum {
SOUBOR_NENALEZEN = 1,
SPATNE_ARGUMENTY = 2,
LIMIT_NAZEV_SOUBOR = 3,
SPATNY_OP = 4
};
void error(int type);
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice);
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument);
void vypisMatice(int radky, int sloupce, int **matice);
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR]);
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR]);
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op);
int main(int argc, char** argv)
{
int n, m; // n = sloupce, m = radky pro prvni matici
int** first;
char nazevSouboru[MAX_SOUBOR], nazevVystupni[MAX_SOUBOR];
char op;
first = NULL;
zpracovaniArgumentu(argc, argv, &nazevSouboru, &nazevVystupni, &n, &m, &*first);
/* for (int i = 0; i < m; i++) {
free(first[i]);
} */
free(first);
system("pause");
return 0;
}
void error(int type)
{
switch (type)
{
case SOUBOR_NENALEZEN: printf("Soubor nenalezen!");
break;
case SPATNE_ARGUMENTY: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
case MAX_DELKA_SOUBORU: printf("Prekrocen maximalni limit delky nazvu souboru (%i).\n", MAX_SOUBOR);
break;
case SPATNY_OP: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
default: printf("Nastala chyba!");
break;
}
system("pause");
exit(type);
}
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice)
{
int firstIter = TRUE;
int doSouboru = FALSE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniMaticeZeSouboru(*m, *n, &*second, *nazevSouboru);
operaceMatic(*m, *n, matice, &*second, &*matice, op);
}
else if (argv[x][0] == '-')
{
switch (argv[x][1])
{
case 'n': doSouboru = TRUE;
break;
default: error(SPATNE_ARGUMENTY);
break;
}
}
else if (doSouboru)
{
setNazevSouboru(nazevVystupni, argv[x]);
}
else
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniVelikostiMatice(n, m, *nazevSouboru);
matice = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matice[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
nacteniMaticeZeSouboru(*m, *n, &*matice, *nazevSouboru);
firstIter = FALSE;
}
}
vypisMatice(*m, *n, matice);
for (int i = 0; i < *n; i++) {
printf("%i",second[i]);
free(second[i]);
}
free(second);
}
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument)
{
strcpy(*nazev, argument);
strcat(*nazev, ".txt"); //nazev souboru
}
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR])
{
FILE *fp = fopen(nazev, "r"); // načtení souboru
int c;
int radky = 1;
int sloupce = 0;
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
while ((c = fgetc(fp)) != EOF)
{
//tolower(c);
if (c == '\n')
{
radky++;
}
else if ((isdigit(c)) && (radky == 1))
{
sloupce++;
}
}
}
fclose(fp);
*n = sloupce;
*m = radky;
return 0;
}
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR])
{
int x;
FILE *fp = fopen(nazev, "r"); // načtení souboru
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &matice[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
}
fclose(fp);
return 0;
}
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op)
{
int vysledekClip[10][10];
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
switch (op) {
case '+': vysledekClip[c][d] = prvni[c][d] + druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '-': vysledekClip[c][d] = prvni[c][d] - druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '/': vysledekClip[c][d] = prvni[c][d] / druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '%': vysledekClip[c][d] = prvni[c][d] % druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '*': vysledekClip[c][d] = prvni[c][d] * druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
default: error(SPATNY_OP);
break;
}
vysledek[c][d] = vysledekClip[c][d];
}
}
return 0;
}
void vypisMatice(int radky, int sloupce, int **matice)
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
void vypisMaticeDoSouboru(int radky, int sloupce, int **matice, char nazevSouboru[MAX_DELKA_SOUBORU])
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
You have a problem with the 'second' array. You allocate an array of *n pointers to int but fill *m elements in that array:
second = (int **) malloc(*n * sizeof(int*));<p>
for (int i = 0; i < *m; i++) {

Expected identification or '(' before return 0?

I am trying to compile this on C, but I can't see where is wrong.
#include <stdio.h>
int verifica_quatro (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_tres (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_dois (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_grupo (int N, int M)
{
if (M == 0)
M= 100;
if (N == 0)
N= 100;
N= (N-1)/4;
M= (M-1)/4;
if (N == M)
return 1;
else
return -1;
}
int main(void)
{
int V, N, M, r;
int valor = -1;
int cont = 4;
scanf("%d %d %d", &V, &N, &M);
while !(M==0 && N==0 && V==0) {
while (M>=10000) {
M= M/10;
}
while (N>=10000) {
N= N/10;
}
while (cont>0 && valor<0){
if (cont == 4){
r = verifica_quatro(N,M);
valor = V*2500*r;
}else if(cont == 3){
N = N/10;
M = M/10;
r = verifica_tres(N,M);
valor = V*510*r;
}else if(cont == 2){
N = N/100;
M = M/100;
r = verifica_dois(N,M);
valor = V*77*r;
}else if(cont == 1){
N = N/100;
M = M/100;
r = verifica_grupo(N,M);
valor = V*34*r;
}
cont--;
}
}
if (valor<0)
valor = 0;
printf ("%d\n", valor);
printf ("Digite M, N e V");
scanf ("%d %d %d", &M, &N, &V);
}
return 0;
}
Here is your code that compile successfully.
#include <stdio.h>
int verifica_quatro (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_tres (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_dois (int N, int M)
{
if (M==N)
return 1;
else
return -1;
}
int verifica_grupo (int N, int M)
{
if (M == 0)
M= 100;
if (N == 0)
N= 100;
N= (N-1)/4;
M= (M-1)/4;
if (N == M)
return 1;
else
return -1;
}
int main(void)
{
int V, N, M, r;
int valor = -1;
int cont = 4;
scanf("%d %d %d", &V, &N, &M);
while (!(M==0 && N==0 && V==0)) //Here a problem with ()
{
while (M>=10000)
{
M= M/10;
}
while (N>=10000)
{
N= N/10;
}
while (cont>0 && valor<0)
{
if (cont == 4)
{
r = verifica_quatro(N,M);
valor = V*2500*r;
}
else if(cont == 3)
{
N = N/10;
M = M/10;
r = verifica_tres(N,M);
valor = V*510*r;
}
else if(cont == 2)
{
N = N/100;
M = M/100;
r = verifica_dois(N,M);
valor = V*77*r;
}
else if(cont == 1)
{
N = N/100;
M = M/100;
r = verifica_grupo(N,M);
valor = V*34*r;
}
cont--;
}
}
if (valor<0)
valor = 0;
printf ("%d\n", valor);
printf ("Digite M, N e V");
scanf ("%d %d %d", &M, &N, &V);
//} This should be deleted
return 0;
}
In your outer while loop you write
while !(M==0 && N==0 && V==0)
Which is syntax error it should be
while (!(M==0 && N==0 && V==0))
And braces before return 0 is extra, it should be removed.
You have a missing set of parentheses in
while !(M==0 && N==0 && V==0)
fix it this way:
while (!(M==0 && N==0 && V==0))
Or more confusingly:
while (M|N|V)
Also: indent your code with four spaces per level and NO TABS!
These two lines at the end are not in any function. Plus what chqrlie said..
return 0;
}

Resources