RPN with header, Why doesn't it work? - c

I did a RPN, but doesn't show the result and the steps, before was appearing, I don't understand what is happening and there are no errors thrown by compiler either.
I do always this example:
3.2 1.8 - 10 / 2 + .
4 steps
= 2.14
I really don't know what's wrong ...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
// quando dá enter ele fecha
// não está imprimindo o resultado O__O
typedef double pilha_t;
#define PILHA_VAZIA INT_MIN
#define N 100
#define TRUE 1
#define FALSE 0
struct Pilha {
pilha_t pilha[N];
int tamanho;
};
void inicializar(struct Pilha *p) {
p->tamanho = 0;
}
int cheia(struct Pilha *p) {
if (p->tamanho == N)
return TRUE;
return FALSE;
}
int vazia(struct Pilha *p) {
if (p->tamanho == 0)
return TRUE;
return FALSE;
}
void empilhar(struct Pilha *p, pilha_t num) {
if (cheia(p))
printf("Atencao: Pilha cheia!\n");
else {
p->pilha[p->tamanho] = num;
p->tamanho++;
}
}
pilha_t desempilhar(struct Pilha *p) {
if (vazia(p)) {
printf("Atencao: Pilha vazia!\n");
return PILHA_VAZIA;
}
else {
p->tamanho--;
return p->pilha[p->tamanho];
}
}
void imprimir(struct Pilha *p) {
int i;
printf("Pilha");
for(i=0; i < p->tamanho; i++)
printf(" %lf", p->pilha[i]);
printf("\n");
}
int main(int argc, char **argv)
{
struct Pilha p;
char str[30];// nao esta sendo usada,msg amarela
inicializar (&p);
char ch1[30];
printf("Digite a expressao: ");
fgets(ch1, 30, stdin);
int i, linha;
char s[30];
int k;
for(k=0;k<30;k++)
s[k]=' ';
for (i=0; i<30; i++) {
char C = ch1[i];
//printf(" %c \n", C);
if (isdigit(C) || C == '.'){
s[linha++] = C;
} else if (s[0] == '.') {
double total;
total = desempilhar(&p);
printf( "Total = %.2lf\n", total);
break;
}
else if (C == ' ') {
if (atof(s) != 0)
empilhar(&p, atof(s));
linha = 0;
int k;
for(k=0;k<30;k++)
s[k]=' ';
}
else if ((C == '+') || (C == '-') || (C == '*') || (C == '/')) {
double n1, n2, total;
n2 = desempilhar(&p);
n1 = desempilhar(&p);
switch (ch1[i]) {
case '+': total = n1 + n2; break;
case '-': total = n1 - n2; break;
case '*': total = n1 * n2; break;
case '/': total = n1 / n2; break;
default : printf( "erro no operador\n");
exit( EXIT_FAILURE);
}
empilhar(&p, total);
}
else
break;
}
return (0);
}

The line int i, linha; should be :
int i, linha = 0;
EDIT :
As you never use imprimir in your code, steps could not appear. I make some slight modifications in your code apart from the fix above :
add a #define DEBUG 1 near the beginning of program to control trace prints
protect the #define DEBUG 1 with a #ifndef block to allow to define it at compilation time
reverse the order of imprimir and empilhar to allow the use of imprimir in the body of empilhar
add a call to imprimir in empilhar
Here is the resulting code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
// quando dá enter ele fecha
// não está imprimindo o resultado O__O
typedef double pilha_t;
#define PILHA_VAZIA INT_MIN
#define N 100
#define TRUE 1
#define FALSE 0
#ifndef DEBUG
#define DEBUG 1
#endif
struct Pilha {
pilha_t pilha[N];
int tamanho;
};
void inicializar(struct Pilha *p) {
p->tamanho = 0;
}
int cheia(struct Pilha *p) {
if (p->tamanho == N)
return TRUE;
return FALSE;
}
int vazia(struct Pilha *p) {
if (p->tamanho == 0)
return TRUE;
return FALSE;
}
pilha_t desempilhar(struct Pilha *p) {
if (vazia(p)) {
printf("Atencao: Pilha vazia!\n");
return PILHA_VAZIA;
}
else {
p->tamanho--;
return p->pilha[p->tamanho];
}
}
void imprimir(struct Pilha *p) {
int i;
printf("Pilha");
for(i=0; i < p->tamanho; i++)
printf(" %lf", p->pilha[i]);
printf("\n");
}
void empilhar(struct Pilha *p, pilha_t num) {
if (cheia(p))
printf("Atencao: Pilha cheia!\n");
else {
p->pilha[p->tamanho] = num;
p->tamanho++;
if (DEBUG) {
imprimir(p);
}
}
}
int main(int argc, char **argv)
{
struct Pilha p;
char str[30];// nao esta sendo usada,msg amarela
inicializar (&p);
char ch1[30];
printf("Digite a expressao: ");
fgets(ch1, 30, stdin);
int i, linha = 0;
char s[30];
int k;
for(k=0;k<30;k++)
s[k]=' ';
for (i=0; i<30; i++) {
char C = ch1[i];
//printf(" %c \n", C);
if (isdigit(C) || C == '.'){
s[linha++] = C;
} else if (s[0] == '.') {
double total;
total = desempilhar(&p);
printf( "Total = %.2lf\n", total);
break;
}
else if (C == ' ') {
if (atof(s) != 0)
empilhar(&p, atof(s));
linha = 0;
int k;
for(k=0;k<30;k++)
s[k]=' ';
}
else if ((C == '+') || (C == '-') || (C == '*') || (C == '/')) {
double n1, n2, total;
n2 = desempilhar(&p);
n1 = desempilhar(&p);
switch (ch1[i]) {
case '+': total = n1 + n2; break;
case '-': total = n1 - n2; break;
case '*': total = n1 * n2; break;
case '/': total = n1 / n2; break;
default : printf( "erro no operador\n");
exit( EXIT_FAILURE);
}
empilhar(&p, total);
}
else
break;
}
return (0);
}
Here is an example of use :
Digite a expressao: 3.2 1.8 - 10 / 2 + .
Pilha 3.200000
Pilha 3.200000 1.800000
Pilha 1.400000
Pilha 1.400000 10.000000
Pilha 0.140000
Pilha 0.140000 2.000000
Pilha 2.140000
Total = 2.14

Related

Why does this code not work in Linux if it shows an error message

I have to make the labyrinth program, which works in Windows under Code Blocks; but when I want to run it in Linux it doesn't work.
When I start debugging, it works correctly until line 63 returns and crashes.
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
Quit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max_col 50
#define max_row 50
#define max_numOflabyrinth 50
#define max_checkPt 50
#define MAX_LINES 10
#define MAX_LINE_LENGTH 2506
enum{UP, DOWN, LEFT, RIGHT};
typedef struct POSITION{
int x;
int y;
} POSITION;
typedef struct PFAD{
POSITION* pos;
int step;
} PFAD;
typedef struct CHECKPOINT{
int seqNum;
int total_span;
int next_span;
int stepNum;
POSITION pos;
POSITION next_steps[3];
//CHECKPOINT* previous_checkPt; //C don't support this.
} CHECKPOINT;
typedef struct LIS_CHECKPOINT{
CHECKPOINT checkPt;
CHECKPOINT* prev_checkPt;
} LIS_CHECKPOINT;
typedef struct LABYRINTH{
char name[10];
char** landkarte; //2D-array landkarte[y][x] y=row x=col
int max_x;
int max_y;
int max_step; //max. laufzeit für while()
POSITION start;
POSITION end;
} LABYRINTH;
int pos_cmp(POSITION a, POSITION b){
if(a.x == b.x && a.y == b.y){return 1;}
else{return 0;}
}
void pos_set(POSITION* des, const POSITION src){
des->x = src.x;
des->y = src.y;
}
void init_LABYRINTH(LABYRINTH* laby){
laby->landkarte=NULL;
laby->max_x=0;
laby->max_y=0;
laby->max_step=0;
laby->start.x=0;
laby->start.y=0;
laby->end.x=0;
laby->end.y=0;
}
/*
int erkunden(LABYRINTH* labyrinth){
POSITION cur_pos;
pos_set(&cur_pos, labyrinth->start);
POSITION check_steps[3]; //only three directions
PFAD footprt;
footprt.pos = calloc(labyrinth->max_x*labyrinth->max_y, sizeof(POSITION));
footprt.step = 0;
CHECKPOINT* prt_last_
}
*/
int erkunden(LABYRINTH* labyrinth){
fflush(stdin);
POSITION cur_pos;
//initialisieren
pos_set(&cur_pos, labyrinth->start);
POSITION check_steps[3]; //max. möglich 3 Richtung
PFAD footprt;
footprt.pos = calloc(labyrinth->max_x*labyrinth->max_y, sizeof(POSITION));
footprt.step = 0;
CHECKPOINT* ptr_last_checkPt;
LIS_CHECKPOINT* lis_checkPt;
lis_checkPt = calloc(max_checkPt, sizeof(LIS_CHECKPOINT));
int total_checkPt=0;
int i, j;
int if_break=1;
int numOFsteps=0;
int loopcontroll=0;
char** map= calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
map[i]=calloc(labyrinth->max_x, sizeof(char));
}
while(!pos_cmp(cur_pos, labyrinth->end) && if_break){
map[cur_pos.y][cur_pos.x]=1;
pos_set(&footprt.pos[footprt.step], cur_pos);
//oben
if(cur_pos.y-1>=0 && labyrinth->landkarte[cur_pos.y-1][cur_pos.x]!='w' && map[cur_pos.y-1][cur_pos.x]!=1){
check_steps[numOFsteps].x=cur_pos.x;
check_steps[numOFsteps].y=cur_pos.y-1;
numOFsteps++;
}
//unten
if(cur_pos.y+1<labyrinth->max_y && labyrinth->landkarte[cur_pos.y+1][cur_pos.x]!='w' && map[cur_pos.y+1][cur_pos.x]!=1){
check_steps[numOFsteps].x=cur_pos.x;
check_steps[numOFsteps].y=cur_pos.y+1;
numOFsteps++;
}
//links
if(cur_pos.x-1>=0 && labyrinth->landkarte[cur_pos.y][cur_pos.x-1]!='w' && map[cur_pos.y][cur_pos.x-1]!=1){
check_steps[numOFsteps].x=cur_pos.x-1;
check_steps[numOFsteps].y=cur_pos.y;
numOFsteps++;
}
//rechts
if(cur_pos.x+1<labyrinth->max_x && labyrinth->landkarte[cur_pos.y][cur_pos.x+1]!='w' && map[cur_pos.y][cur_pos.x+1]!=1){
check_steps[numOFsteps].x=cur_pos.x+1;
check_steps[numOFsteps].y=cur_pos.y;
numOFsteps++;
}
if(numOFsteps==0){
do{
ptr_last_checkPt=lis_checkPt[ptr_last_checkPt->seqNum].prev_checkPt;
j=(++ptr_last_checkPt->next_span);
}
while(ptr_last_checkPt->next_span > ptr_last_checkPt->total_span-1);
pos_set(&cur_pos, ptr_last_checkPt->next_steps[j]);
footprt.step=ptr_last_checkPt->stepNum;
}
else if(numOFsteps==1){
pos_set(&cur_pos, check_steps[0]);
}
else {
ptr_last_checkPt = &lis_checkPt[total_checkPt].checkPt;
ptr_last_checkPt->seqNum=total_checkPt;
if(total_checkPt==0){
lis_checkPt[total_checkPt].prev_checkPt=NULL;}
else{
lis_checkPt[total_checkPt].prev_checkPt=&lis_checkPt[total_checkPt-1].checkPt;
}
for(i=0;i<numOFsteps;i++){
pos_set(&ptr_last_checkPt->next_steps[i], check_steps[i]);
}
pos_set(&ptr_last_checkPt->pos, cur_pos);
ptr_last_checkPt->total_span=numOFsteps;
ptr_last_checkPt->next_span=0;
ptr_last_checkPt->stepNum=footprt.step;
pos_set(&cur_pos, ptr_last_checkPt->next_steps[0]);
total_checkPt++;
}
numOFsteps=0;
footprt.step++;
loopcontroll++;
if(loopcontroll>labyrinth->max_step) if_break=0;
}//end loop
//save the solution in the labyrith
for(i=0;i<footprt.step;i++){
labyrinth->landkarte[footprt.pos[i].y][footprt.pos[i].x]='*';
}
//free
free(footprt.pos);
free(lis_checkPt);
for(i=0;i<labyrinth->max_y;i++) free(map[i]);
free(map);
//rückgabewert
if(loopcontroll>labyrinth->max_step) return 1;
else return 0;
}
FILE* open_labyrinth_file(char* file_name){
FILE* file_landkarte = fopen(file_name, "r");
if (file_landkarte==NULL){
printf("Fehler bei Einlesen der Text-Datei\n");
return NULL;
}
printf("\"%s\" eingelesen!\n",file_name);
return file_landkarte;
}
LABYRINTH* load_labyrinth(const char* map_line, int max_x_size, int max_y_size){
LABYRINTH* labyrinth=NULL;
init_LABYRINTH(labyrinth);
int map_size = strlen(map_line)-1; //
int i=0,j=0,k=0; //variables to help
labyrinth->max_step=0;
int b=0, z=0;
//name for the Labyrinth
for(i=0;i<6;i++){
if(map_line[i] == '='){
labyrinth->name[i] = '\0';
break;
}else{
labyrinth->name[i] = map_line[i];
}
}
k = strlen(labyrinth->name)+1;
map_size -= k;
for(i=k; i<max_x_size; i++){
//if the labyrinth is not quadratic i.e. has an exact root
if(i*i == map_size){
labyrinth->max_x=i;
labyrinth->max_y=i;
break;
}
if(i*i>map_size){
printf("Dimensions incorrect: map not quaratic!: %s \n", labyrinth->name);
return NULL;
}
}
//loop to check that the maze contains one exit and one entrance
for(i=k;i<map_size;i++){
if(map_line[i]=='b'){b=1;}
if(map_line[i]=='z'){z=1;}
}
if(b!=1||z!=1){
printf("The map not contains an start and an end: %s \n", labyrinth->name);
return NULL;
}else{
printf("The map contains an start and an end: %s \n", labyrinth->name);
}
labyrinth->landkarte = calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
labyrinth->landkarte[i] = calloc(labyrinth->max_x, sizeof(char*));
}
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
labyrinth->landkarte[i][j]=map_line[i*labyrinth->max_x+j+k];
if(labyrinth->landkarte[i][j]=='b'){
labyrinth->start.x=j;
labyrinth->start.y=i;
}
if(labyrinth->landkarte[i][j]=='z'){
labyrinth->end.x=j;
labyrinth->end.y=i;
}
if(labyrinth->landkarte[i][j]=='k'){
labyrinth->max_step+=2;
}
}
}
return labyrinth;
}
/*
LABYRINTH* load_labyrinth(const char* landkarte_zeile, int max_x_size, int max_y_size){
int landkarte_size=strlen(landkarte_zeile);
int i,j,k;
LABYRINTH* labyrinth;
init_LABYRINTH(labyrinth);
labyrinth->max_step=0;
if(max_x_size!=max_y_size){
printf("Dimensionsangaben fehlerhaft: max_x und max_y muss identisch sein!/n");
return NULL;
}
for(i=0;i<5;i++){
if(landkarte_zeile[i]=='='){
labyrinth->name[i]='\0';
break;
}
labyrinth->name[i] = landkarte_zeile[i];
}
k=strlen(labyrinth->name)+1;
landkarte_size-=k;
for(i=3;i<=max_x_size;i++){
if(i*i==landkarte_size){
labyrinth->max_x=i;
labyrinth->max_y=i;
break;
}
if(i*i>landkarte_size){
printf("Dimensionen fehlerhaft: Landkarte nicht quaratisch!: %s \n",labyrinth->name);
return NULL;
}
}
labyrinth->landkarte = calloc(labyrinth->max_y, sizeof(char*));
for(i=0;i<labyrinth->max_y;i++){
labyrinth->landkarte[i] = calloc(labyrinth->max_x, sizeof(char*));
}
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
labyrinth->landkarte[i][j]=landkarte_zeile[i*labyrinth->max_x+j+k];
if(labyrinth->landkarte[i][j]=='b'){
labyrinth->start.x=j;
labyrinth->start.y=i;
}
if(labyrinth->landkarte[i][j]=='z'){
labyrinth->end.x=j;
labyrinth->end.y=i;
}
if(labyrinth->landkarte[i][j]=='k'){
labyrinth->max_step+=2;
}
}
}
return labyrinth;
}
*/
/*
//old
char* print_labyrinth(LABYRINTH* labyrinth){
if(labyrinth==NULL){
printf("Plot-Fehler: kein Labyrith gefunden.\n");
return;
}
char buffer[100];
char character = 'c';
int i,j;
printf("Labyrinth: %s\n", labyrinth->name);
//strcat(buffer, labyrinth->name);
for(i=0;i<labyrinth->max_y;i++){
for(j=0;j<labyrinth->max_x;j++){
if(labyrinth->landkarte[i][j]=='w'){
character = '#';
printf(character);
strncat(buffer, &character, 1);
}
else if(labyrinth->landkarte[i][j]=='k'){
printf(" ");
//strcat(buffer, ' ');
}
else{
printf("%c", labyrinth->landkarte[i][j]);
//strcat(buffer, labyrinth->landkarte[i][j]);
}
}
printf("\n");
//strcat(buffer,"\n");
}
printf("Start: (%i,%i) ", labyrinth->start.x,labyrinth->start.y);
printf("End: (%i,%i)\n", labyrinth->end.x,labyrinth->end.y);
return buffer;
} */
//new
char* print_labyrinth(LABYRINTH* labyrinth) {
if (labyrinth == NULL) {
return strdup("Plot-Fehler: kein Labyrinth gefunden.\n");
}
char* buffer = malloc(sizeof(char) * 10000);
if (buffer == NULL) {
// handle error
}
int offset = 0;
offset += sprintf(buffer + offset, "Labyrinth: %s\n", labyrinth->name);
for (int i = 0; i < labyrinth->max_y; i++) {
for (int j = 0; j < labyrinth->max_x; j++) {
if (labyrinth->landkarte[i][j] == 'w') {
offset += sprintf(buffer + offset, "#");
} else if (labyrinth->landkarte[i][j] == 'k') {
offset += sprintf(buffer + offset, " ");
} else {
offset += sprintf(buffer + offset, "%c", labyrinth->landkarte[i][j]);
}
}
offset += sprintf(buffer + offset, "\n");
}
offset += sprintf(buffer + offset, "Start: (%i,%i) End: (%i,%i)\n",
labyrinth->start.x, labyrinth->start.y, labyrinth->end.x, labyrinth->end.y);
printf("%s", buffer);
return buffer;
}
void save_to_file(char* text, char* filename) {
FILE* file = fopen(filename, "wt");
if (file == NULL) {
printf("Error opening file.\n");
return;
}
fprintf(file, "%s", text);
fclose(file);
printf("Text saved to file %s\n", filename);
}
int main()
{
/*
int i,j,k;
int *ergibnis;
int total_labyr=0;
char charbuff[2506]={'\0'};
char* solution = malloc(sizeof(char) * 10000);
int offset = 0;
LABYRINTH** labyrinth[max_numOflabyrinth];
FILE* file_landkarte = open_labyrinth_file("labyrinth_karte.txt");
if(fgets(charbuff,2506,file_landkarte)!=EOF){
labyrinth[total_labyr]=load_labyrinth(charbuff, 50, 50);
total_labyr++;
}
ergibnis = calloc(total_labyr, sizeof(int));
for(i=0;i<total_labyr;i++){
if(!erkunden(labyrinth[i])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
ergibnis[i] = 1;
offset += sprintf(solution + offset, print_labyrinth(labyrinth[j]));
}
}
print_labyrinth(labyrinth);
save_to_file(solution, "solvelab.txt");
*/
LABYRINTH* labyrinth[MAX_LINES];
init_LABYRINTH(&labyrinth);
int i=0, j=0;
char charbuff[2506];
char* solution;
solution =(char*)malloc(sizeof(char) * 2506);
int offset = 0;
FILE* file_landkarte = open_labyrinth_file("labyrinth_karte.txt");
/* for(j=0; j< MAX_LINES; j++){
fflush(stdin);
init_LABYRINTH(labyrinth[j]);
}
*/
while (fgets(charbuff, MAX_LINE_LENGTH, file_landkarte) != NULL) {
labyrinth[i] = load_labyrinth(charbuff, max_row, max_col);
if(labyrinth[i]!=NULL){
print_labyrinth(labyrinth[i]);
if(!erkunden(labyrinth[i])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
//solution = print_labyrinth(labyrinth[j]);
//strcpy(,print_labyrinth(labyrinth[j]));
offset += sprintf(solution + offset, print_labyrinth(labyrinth[i]));
printf("labyrinth solved!\n");
save_to_file(solution, "solvelab.txt");
}
else{
printf("labyrinth has no solution!\n");
}
}else{
printf("no posible: %i \n",j);
}
i++;
}
/*
for (j = 0; j < 6 ;j ++){
// labyrinth = load_labyrinth(lines[j],max_row, max_col);
if(labyrinth[j]!=NULL){
print_labyrinth(labyrinth[j]);
if(!erkunden(labyrinth[j])){ // ! weil erkunden liefert 0 wenn erfolgreich ist
//solution = print_labyrinth(labyrinth[j]);
//strcpy(,print_labyrinth(labyrinth[j]));
offset += sprintf(solution + offset, print_labyrinth(labyrinth[j]));
printf("labyrinth solved!\n");
//save_to_file(solution, "solvelab.txt");
}
else{
printf("labyrinth has no solution!\n");
}
}else{
printf("no posible\n: %i ",j);
}
}
*/
//save_to_file(solution, "solvelab.txt");
fclose(file_landkarte);
return 0;
}
labyrinth_karte.txt
L3=wwwwwwwskkkwwwkwswwskwwwwwkkzwwwwwww
L4=wwwwbwwskkkwwwkwswwskwwwwwkkswwwwwww
L5=wwwbwwwskkkwwwwwswwskwwwwwkkzwwwwwww
L6=wwwbwwkskkkwwwkwswwskwwwwwkkzwwwwwww
L1=wwwbwwwskkkwwwkwswwskwwwwwkkzwwwwwww
L2=wwwwwwwwwswkkkswwkwkwzwwwkkkwwswbkwwswkwwkkkkwkwwswwkkkwwwwwwwww

trying to free dynamic allocated memory

So i know this might be asking too much but in my program i used valgrind for some reason it always says that i have 9 allocs mad and 1 free made, but in my code i freed all of the arrays i used, so i dont know are the allocs not being freed.
So if anyone could help me i would appreciate it a lot because im not understanding whats wrong in my code.
Program:
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
#define MAX_CHARS 1024 /* max characters of a word */
#define MAX_SIZE 5
static int line = 1; /* counts the number of lines of the stdin */
int ident = 0; /*counts the id of jogos*/
static int size_until = 0; /*counts the size of sistema_eq*/
static int size_until2 = 0;/*counts the size of conj_jogos*/
char **sistema_eq;
typedef struct
{
int id;
char equipas[2][1024];
int pont[2];
char nome[MAX_CHARS];
} jogo;
typedef struct
{
int id;
char nome[MAX_CHARS];
int vit;
} vitorias;
/*-----------------------------------------*/
jogo *conj_jogos;
vitorias *conj_vit;
void a(char nome_jg[],char team1[],char team2[],int score1,int score2);
void A(char nome[]);
int main()
{
char c;
char nome_jg[MAX_CHARS], team1[MAX_CHARS], team2[MAX_CHARS];
int score1;
int score2;
int i;
conj_jogos = (jogo*)calloc(MAX_SIZE,sizeof(jogo));
conj_vit = (vitorias*)calloc(MAX_SIZE,sizeof(vitorias));
sistema_eq = (char**)calloc(MAX_SIZE,sizeof(*sistema_eq));
for(i=0;i<MAX_SIZE;i++)
{
sistema_eq[i] = (char*)calloc(1024,sizeof(char));
}
while ((c = getchar())!= 'x') {
switch (c)
{
case 'A':
{
scanf("%1023[^:\n]",nome_jg);
remove_esp(nome_jg);
A(nome_jg);
break;
}
case 'a':
{
scanf("%1023[^:\n]:%1023[^:\n]:%1023[^:\n]:%d:%d",nome_jg,team1,team2,&score1,&score2);
remove_esp(nome_jg);
a(nome_jg,team1,team2,score1,score2);
line++;
break;
}
}
}
free(conj_vit);
free(conj_jogos);
for(i=0;i<size_until;i++) free(sistema_eq[i]);
free(sistema_eq);
return 0;
}
void A(char nome[])
{
if (nome_in_sis(nome) == 1)
{
printf("%d Equipa existente.\n",line);
line++;
}
else
{
if (size_until < MAX_SIZE)
{
strcpy(sistema_eq[size_until],nome);
strcpy(conj_vit[size_until].nome,nome);
conj_vit[size_until].id = size_until;
size_until++;
line++;
}
else
{
conj_vit = realloc(conj_vit,sizeof(vitorias)*(size_until+1));
sistema_eq = realloc(sistema_eq,sizeof(char*)*(size_until+1));
sistema_eq[size_until] = calloc(1024,sizeof(char*));
strcpy(sistema_eq[size_until],nome);
strcpy(conj_vit[size_until].nome,nome);
conj_vit[size_until].id = size_until;
size_until++;
line++;
}
}
}
void a(char nome_jg[],char team1[],char team2[],int score1,int score2)
{
int vit;
if (jogo_in(nome_jg) == 1)
{
printf("%d Jogo existente.\n",line);
line++;
}
else if ((nome_in_sis(team1) == 0) || (nome_in_sis(team2) == 0))
{
printf("%d Equipa inexistente.\n",line);
line++;
}
else
{
if (size_until2 < MAX_SIZE)
{
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
if (score1 > score2)
{
vit = procura_vit(team1);
conj_vit[vit].vit++;
}
else
{
vit = procura_vit(team2);
conj_vit[vit].vit++;
}
size_until2++;
}
else
{
size_until2++;
conj_jogos = realloc(conj_jogos,sizeof(jogo)*(size_until2+1));
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
if (score1 > score2)
{
vit = procura_vit(team1);
conj_vit[vit].vit++;
}
else
{
vit = procura_vit(team2);
conj_vit[vit].vit++;
}
size_until2++;
}
}
}

Game of Life .exe strange output

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);
}

error : expected identifier or '(' in global variable

I got this errror during compile processing.
I already saw this error in this site before, I think this error can occur when the ; or something are in wrong place. but I can't find.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define MAX 80
typedef struct assemble
{
int op;
int ni;
int xbpe;
int addr;
}Assemble;
void get_token(char *bp);
int hTod(char *dp);
int bTod(char *dp);
void codeBreak(char *cp);
void result(int t);
Assemble asm;
int type;
int main()
{
FILE *fp;
char buf[MAX];
if( (fp = fopen("inst.txt","r")) == NULL ){
fprintf(stderr, "file not found...\n"); exit(1);
}
while(fgets(buf,sizeof(buf),fp) != NULL){
get_token(buf);
}
fclose(fp);
return 0;
}
void get_token(char *bp)
{
char *cp;
int i = 1;
for(cp=strtok(bp, " \t\n"); cp != NULL; )
{
if( (*(cp+0) == '0') && (*(cp+1) == 'x') )
{
if( i == -1 )
asm.addr = hTod(cp);
if( i == 1)
asm.op = hTod(cp);
i *= -1;
}
else
{
codeBreak(cp);
}
cp = strtok(NULL, " \t\n");
}
result(type);
}
void codeBreak(char *cp)
{
if ( strlen(cp) == 2 ) // ni 판단
{
asm.ni = bTod(cp);
}
else if( strlen(cp) == 1 )
{
asm.xbpe = bTod(cp)*pow(2,3);
type = 1;
}
else if( strlen(cp) == 4 )
{
if( *(cp+3) == '1')
{
asm.xbpe = bTod(cp);
type = 2;
}
else
{
asm.xbpe = bTod(cp);
type = 3;
}
}
}
void result(int t)
{
switch(t)
{
case 1 : printf("0x%x%x\n", (asm.op+asm.ni), asm.addr); break;
case 2 : printf("0x%x%x%.5x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
case 3 : printf("0x%x%x%.3x\n", (asm.op+asm.ni), asm.xbpe, asm.addr); break;
default : break;
}
}
/* Hex to decimal */
int hTod(char *dp)
{
int i;
int dec = 0;
for( i=2 ; i < strlen(dp) ; i++)
{
switch (*(dp+i))
{
case 'a' : *(dp+i) = 58; break;
case 'b' : *(dp+i) = 59; break;
case 'c' : *(dp+i) = 60; break;
case 'd' : *(dp+i) = 61; break;
case 'e' : *(dp+i) = 62; break;
case 'f' : *(dp+i) = 63; break;
}
dec += (*(dp+i)-48) * pow( 16, (strlen(dp)-(i+1)));
}
return dec;
}
/* binary to decimal*/
int bTod(char *dp)
{
int i;
int dec = 0;
for( i = 0; i < strlen(dp) ; i++)
{
dec += (*(dp+i)-48) * pow( 2, (strlen(dp) - (i+1)));
}
return dec;
}
asm is a keyword. Instead of
Assemble asm;
use something different, such as:
Assemble asm1;
The problem reported by the compiler is different though. You seem to have used
ASSEMBLY asm;
in the code you compiled.

Expected '(' for function-style or type construction

So I'm trying to call a function in my main function within my switch function and it's telling me "expected '(' for function-style or type construction." What am I doing wrong here causing this error? I can't seem to figure it out. Thanks.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 6
#include <string.h>
typedef struct
{
char name[100];
unsigned int accountId;
float accountBalance;
int yearJoined;
} BankingInfo;
void createTestData(BankingInfo inventory[]){
strcpy(inventory[0].name, "Alex");
inventory[0].accountId = 1001;
inventory[0].accountBalance = 2390;
inventory[0].yearJoined = 2001;
strcpy(inventory[1].name, "Bill");
inventory[1].accountId = 1003;
inventory[1].accountBalance = 10000;
inventory[1].yearJoined = 2012;
strcpy(inventory[2].name, "Craig");
inventory[2].accountId = 1004;
inventory[2].accountBalance = 500;
inventory[2].yearJoined = 1994;
strcpy(inventory[3].name, "David");
inventory[3].accountId = 1008;
inventory[3].accountBalance = 5836;
inventory[3].yearJoined = 2013;
strcpy(inventory[4].name, "Eric");
inventory[4].accountId = 1016;
inventory[4].accountBalance = 90;
inventory[4].yearJoined = 1999;
strcpy(inventory[5].name, "Felix");
inventory[5].accountId = 1032;
inventory[5].accountBalance = 5703;
inventory[5].yearJoined = 2003;
}
void outputTable(BankingInfo inventory[], int size){
int i;
printf("Names\tID\t\tAccount Balance\t\tYear Joined\n");
for (i = 0; i < ARRAY_SIZE; i++) {
printf("%s\t%u\t %.2lf\t\t\t%i\n",
inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
void searchById(BankingInfo inventory[], int size, int id){
unsigned int enteredId;
int i;
printf("Enter ID number: ");
scanf("%u", &enteredId);
for (i = 0; i < ARRAY_SIZE; i++) {
if (inventory[i].accountId == enteredId) {
printf(inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
}
void searchByYear(BankingInfo inventory[], int size, int year){
unsigned int enteredYear;
int i;
printf("Enter year joined: ");
scanf("%u", &enteredYear);
for (i = 0; i < ARRAY_SIZE; i++) {
if (inventory[i].yearJoined == enteredYear) {
printf(inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
}
int main(void){
int choice;
BankingInfo inventory[ARRAY_SIZE];
createTestData(inventory);
outputTable(inventory, ARRAY_SIZE);
do{
printf("Enter 1 to search by ID\n");
printf("Enter 2 to search by year joined\n");
printf("Enter 3 to finish\n");
switch (choice) {
case 1:
searchById(inventory, ARRAY_SIZE, int id);
break;
case 2:
searchByYear(inventory, ARRAY_SIZE, int year);
break;
case 3:
break;
default:
printf("Not a valid choice\n");
break;
}
}while (choice != 3);
return 1;
}
You have a type specifier in a function call parameter, twice like this
searchById(inventory, ARRAY_SIZE, int id);
/* ^ this ???? */
just remove it
searchById(inventory, ARRAY_SIZE, id);
and then declare and initialize id and year.
I've fixed your program, I hope you can understand what I did
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 6
#include <string.h>
typedef struct
{
char name[100];
unsigned int accountId;
float accountBalance;
int yearJoined;
} BankingInfo;
void createTestData(BankingInfo inventory[])
{
strcpy(inventory[0].name, "Alex");
inventory[0].accountId = 1001;
inventory[0].accountBalance = 2390;
inventory[0].yearJoined = 2001;
strcpy(inventory[1].name, "Bill");
inventory[1].accountId = 1003;
inventory[1].accountBalance = 10000;
inventory[1].yearJoined = 2012;
strcpy(inventory[2].name, "Craig");
inventory[2].accountId = 1004;
inventory[2].accountBalance = 500;
inventory[2].yearJoined = 1994;
strcpy(inventory[3].name, "David");
inventory[3].accountId = 1008;
inventory[3].accountBalance = 5836;
inventory[3].yearJoined = 2013;
strcpy(inventory[4].name, "Eric");
inventory[4].accountId = 1016;
inventory[4].accountBalance = 90;
inventory[4].yearJoined = 1999;
strcpy(inventory[5].name, "Felix");
inventory[5].accountId = 1032;
inventory[5].accountBalance = 5703;
inventory[5].yearJoined = 2003;
}
void outputTable(BankingInfo inventory[], int size)
{
int i;
printf("Names\tID\t\tAccount Balance\t\tYear Joined\n");
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
void searchById(BankingInfo inventory[], int size, int id)
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
{
if (inventory[i].accountId == id)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
}
void searchByYear(BankingInfo inventory[], int size, int year){
unsigned int enteredYear;
int i;
printf("Enter year joined: ");
scanf("%u", &enteredYear);
for (i = 0; i < ARRAY_SIZE; i++)
{
if (inventory[i].yearJoined == enteredYear)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
}
int main(void)
{
char choice;
BankingInfo inventory[ARRAY_SIZE];
createTestData(inventory);
outputTable(inventory, ARRAY_SIZE);
do {
int id;
int year;
printf("\n");
printf("\t1 Search by ID\n");
printf("\t2 Search by year joined\n");
printf("\t3 Finish\n\n");
printf("Please input your choice > ");
scanf(" %c", &choice);
switch (choice)
{
case '1':
printf("Enter item id > ");
if (scanf("%d", &id) == 1)
searchById(inventory, ARRAY_SIZE, id);
else
printf("invalid input\n");
break;
case '2':
printf("Enter item year > ");
if (scanf("%d", &year) == 1)
searchByYear(inventory, ARRAY_SIZE, year);
else
printf("invalid input\n");
break;
case '3':
break;
default:
printf("Not a valid choice\n");
break;
}
} while (choice != '3');
return 0;
}

Resources