C Recursive WordSearch solver in all directions - c

In the main file, I loop through each line of input until it hits the words, then I pass the word its searching for to startSearch with puzzleArray, the solvedArray I want to get back, the word as string, size as number of rows, and length as number of columns.
Currently, I keep getting segmentation faults/or endless loops. Any help over my algorithm/code would be greatly appreciated.
void startSearch(char** puzzleArray,char** solvedArray,char* string,int size,int length)
{
char* direction = "";
int solved = 1;
int j = 0;
while( j <= 7 && solved != 0)
{
if(j == 0)
{
direction = "up";
}
else if(j == 1)
{
direction = "upRight";
}
else if(j == 2)
{
direction = "right";
}
else if(j == 3)
{
direction = "downRight";
}
else if(j == 4)
{
direction = "down";
}
else if(j == 5)
{
direction = "downLeft";
}
else if(j == 6)
{
direction = "left";
}
else if(j == 7)
{
direction = "upLeft";
}
solved = recursiveSearch(puzzleArray,solvedArray,string,direction,size,length,0,0,0);
j++;
}
}
int recursiveSearch(char** puzzleArray,char** solvedArray,char* string,char* direction,int sizeOfPuzzle,int lengthOfArrayWithSpaces,int rowPos,int colPos,int stringPosition)
{
int lengthOfWord;
int i = rowPos;
int j = colPos;
int found = 0;
int empty = 1;
char c = string[stringPosition];
int position = stringPosition;
lengthOfWord = lengthOfArray(string);
if(string[position+1] == '\0')
{
return 0;
}
while(empty != 0)
{
if(string[stringPosition] == puzzleArray[i][j])
{
found = 1;
}
else if(rowPos < sizeOfPuzzle && colPos < lengthOfArrayWithSpaces)
{
stringPosition = 0;
for(i = rowPos; i < sizeOfPuzzle && found != 1; i++)
{
for(j = colPos; j < puzzleArray[rowPos][colPos] != '\0' && found != 1; j++)
{
if(string[stringPosition] == puzzleArray[i][j])
{
found = 1;
rowPos = i;
colPos = j;
stringPosition = 0;
}
}
}
if(found == 0)
{
empty = 1;
}
}
if(found == 1)
{
position = stringPosition + 1;
if(rowPos-1 >= 0)
{
//printf("\nString:%cPuzzleArray:%c",string[position],puzzleArray[rowPos-1][colPos]);
if(string[position] == puzzleArray[rowPos-1][colPos] && direction == "up")
{
//printf("UP");
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos-1,colPos,position+1))
{
solvedArray[rowPos-1][colPos] = puzzleArray[rowPos-1][colPos];
return 0;
}
}
else if(colPos+2 <= lengthOfArrayWithSpaces)
{
if(string[position] == puzzleArray[rowPos-1][colPos+2] && direction == "upRight")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos-1,colPos+2,position+1))
{
solvedArray[rowPos-1][colPos+2] = puzzleArray[rowPos-1][colPos+2];
return 0;
}
}
}
}
if(colPos+2 <= lengthOfArrayWithSpaces)
{
if(string[position] == puzzleArray[rowPos][colPos+2] && direction == "right")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos,colPos+2,position+1))
{
solvedArray[rowPos][colPos+2] = puzzleArray[rowPos][colPos+2];
return 0;
}
}
if(rowPos+1 <= lengthOfArrayWithSpaces)
{
if(string[position] == puzzleArray[rowPos+1][colPos+2] && direction == "downRight")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos+1,colPos+2,position+1))
{
solvedArray[rowPos+1][colPos+2] = puzzleArray[rowPos+1][colPos+2];
return 0;
}
}
}
}
if(rowPos+1 <= sizeOfPuzzle)
{
if(string[position] == puzzleArray[rowPos+1][colPos] && direction == "down")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos+1,colPos,position+1))
{
solvedArray[rowPos+1][colPos] = puzzleArray[rowPos+1][colPos];
return 0;
}
}
if(rowPos + 1 <= lengthOfArrayWithSpaces)
{
if(string[position] == puzzleArray[rowPos+1][colPos-2] && direction == "downLeft")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos+1,colPos-2,position+1))
{
solvedArray[rowPos+1][colPos-2] = puzzleArray[rowPos+1][colPos-2];
return 0;
}
}
}
}
if(colPos-2 >= 0)
{
if(string[position] == puzzleArray[rowPos][colPos-2] && direction == "left")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos+1,colPos+2,position+1))
{
solvedArray[rowPos+1][colPos+2] = puzzleArray[rowPos+1][colPos+2];
return 0;
}
}
if(rowPos - 1 >= 0)
{
if(string[position] == puzzleArray[rowPos-1][colPos-2] && direction == "upLeft")
{
if(recursiveSearch(puzzleArray,solvedArray,string,direction,sizeOfPuzzle,lengthOfArrayWithSpaces,rowPos-1,colPos-2,position+1))
{
solvedArray[rowPos-1][colPos-2] = puzzleArray[rowPos-1][colPos-2];
return 0;
}
}
}
}
}
}
return 1;
}

direction == "up"
This is not how you compare two strings to be equal. Use strcmp / strncmp for string comparison. This kind of comparison appears all over your code.
Also:
for(j = colPos; j < puzzleArray[rowPos][colPos] != '\0' && found != 1; j++)
This j < puzzleArray[rowPos][colPos] != '\0' looks dubious, what are you trying to do?

Related

Error in solution to a problem of matrix of "o's" and "x's" in C language. In this we need to count and identify adjacent elements

Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
Input
The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
Output
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
I have been pondering quite a while as to what I have done wrong, can someone please help me point out the error in my logic in my code.
#include<stdio.h>
int main () {
int n,flag=0;
scanf("%d",&n);
char arr[n][n];
int arr_counter[n][n];
for (int x=0;x<n;x++) {
for (int y=0;y<n;y++) {
arr_counter[x][y] = 0;
}
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
scanf("%c",&arr[i][j]);
}
}
// corners
// top left
if(arr[1][0]=='o') {
arr_counter[0][0] += 1;
}
if(arr[0][1] == 'o') {
arr_counter[0][0] += 1;
}
// top right
if(arr[0][n-2]=='o') {
arr_counter[0][n-1] += 1;
}
if(arr[1][n-1] == 'o') {
arr_counter[0][n-1] += 1;
}
// bottom left
if(arr[n-2][0]=='o') {
arr_counter[n-1][0] += 1;
}
if(arr[n-1][1] == 'o') {
arr_counter[n-1][0] += 1;
}
// bottom right
if(arr[n-2][n-1]=='o') {
arr_counter[n-1][n-1] += 1;
}
if(arr[n-1][n-2] == 'o') {
arr_counter[n-1][n-1] += 1;
}
// edges
for (int a=1;a<n;a++) {
if(arr[0][a+1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[0][a-1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[1][a] == 'o') {
arr_counter[0][a] += 1;
}
}
for (int b=1;b<n;b++) {
if(arr[b-1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b+1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b][1] == 'o') {
arr_counter[b][0] += 1;
}
}
for (int c=1;c<n;c++) {
if(arr[c-1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c+1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c][n-2] == 'o') {
arr_counter[c][n-1] += 1;
}
}
for (int d=1;d<n;d++) {
if(arr[n-1][d+1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-1][d-1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-2][d] == 'o') {
arr_counter[n-1][d] += 1;
}
}
//middle
for (int s=1;s<n-1;s++) {
for (int t=1;t<n-1;t++) {
if(arr[s+1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s-1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t+1] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t-1] == 'o') {
arr_counter[s][t] += 1;
}
}
}
for (int k=0;k<n;k++) {
for (int l=0;l<n;l++) {
if (arr_counter[k][l]%2 != 0) {
flag = 1;
}
}
}
if (flag == 0) {
printf("YES");
} else if (flag == 1) {
printf("NO");
}
}
/*
Test Case 1
input
3
xxo
xox
oxx
output
YES
Test Case 2
input
4
xxxo
xoxo
oxox
xxxx
output
NO
*/

Segmentation fault C language strcat()

#include <stdio.h>
int main() {
char lexer_string[] = "echo Hello %a% %b%";
char temp_variable_name[128] = "...";
int variable_buff = 0;
int check = 0;
int detect_start = 0;
for (int i = 0; i < sizeof(lexer_string); i++) {
// printf("%c\n", lexer_string[i]);
if (lexer_string[i] == '%' && variable_buff == 0) {
check = 1;
variable_buff = 1;
}
if (variable_buff == 1) {
if (lexer_string[i] == '%' && detect_start == 0) {
detect_start = 1;
printf("%%\x20");
}
else if (lexer_string[i] == '%' && detect_start == 1) {
detect_start = 0;
printf(" \%\n");
}
else if (lexer_string[i] != '%') {
printf("%c", lexer_string[i]);
strcat(temp_variable_name, lexer_string[i]);
strcat(temp_variable_name, ' ');
}
}
if (lexer_string[i] == '%' && variable_buff == 1 && check != 1) {
variable_buff = 0;
}
if (lexer_string[i] == '\0') {
printf("Wynik:%s\n", temp_variable_name);
break;
}
check = 0;
}
return 0;
}
This is my simple code, when i use the function strcat() my code stops working. I tried change size of char array's, changed position of function in program (i move them to end but still doesn't work.)

Solve Sudoku using Back tracking Algorithm in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I had a feel to solve sudoku using C programming in early October, and soon I came to know its no easy task. Currently, I did write a code to do all the functioning but there seems to be an error somewhere which is preventing the desired result to get printed or even get evaluated.
I use the algorithm provided here as a reference to develop my code,
This is the code which I have written and correcting the error would be greatly appreciated
#include <stdio.h>
int row(int i,int j,int a[9][9]);
int column(int i,int j,int a[9][9]); //function declaration's
int grid(int i,int j,int a[9][9]);
int main()
{
int a[9][9];
int i,j,x;
for (i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
a[i][j]=0;/*for making all the array values = 0*/
/*So that the stored garbage values will be removed*/
}
}
/*Entering known elements*/
printf("Enter the elements of known elements leaving the unknown as 0\n");
for (i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
scanf("%d",&a[i][j]);
}
}
//If a given grid is '0', lets assign a value 1 and if 1 exists in the same row or column or in ints correspond 3x3 box, increment the value upto 9
i=0,j=0,x=1;
incr:
if ( a[i][j] == 0)
{
a[i][j] = x;
if( row(i,j,a) && column(i,j,a) && grid(i,j,a) )
{
a[i][j] = x;
}
else
{
x++;
if ( x>9)
x = 1;
}
}
else
{
while(i < 9)
{
i++;
goto incr;
}
if (i == 9)
{
i =1;
j++;
goto incr;
}
if (j == 9)
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
}
}
int row(int i,int j,int a[9][9])
{
int m;
for(m=0;m<9;m++)
{
if( m != j)
{
if(a[i][j] == a[i][m])
{
return 0;
}
}
}
return 1;
}
int column(int i,int j, int a[9][9])
{
int m;
printf("%d%d",i,j);
for(m=0;m<9;m++)
{
if ( m != i)
{
if(a[i][j] == a[m][j])
{
return 0;
}
}
}
return 1;
}
int grid(int i,int j, int a[9][9])
{
int m,n;
if( i>=0 && i<=2 && j>=0 && j<=2) /* grid 1*/
{
for(m=0;m<=2;m++)
{
for(n=0;n<=2;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=0 && i<=2 && j>=3 && j<=5) /* grid 2*/
{
for(m=0;m<=2;m++)
{
for(n=3;n<=5;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=0 && i<=2 && j>=6 && j<=8) /* grid 3*/
{
for(m=0;m<=2;m++)
{
for(n=6;n<=8;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=3 && i<=5 && j>=0 && j<=2) /* grid 4*/
{
for(m=3;m<=5;m++)
{
for(n=0;n<=2;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=3 && i<=5 && j>=3 && j<=5) /* grid 5*/
{
for(m=3;m<=5;m++)
{
for(n=3;n<=5;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=3 && i<=5 && j>=6 && j<=8) /* grid 6*/
{
for(m=3;m<=5;m++)
{
for(n=6;n<=8;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=6 && i<=8 && j>=0 && j<=2) /* grid 7*/
{
for(m=6;m<=8;m++)
{
for(n=0;n<=2;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=6 && i<=8 && j>=3 && j<=5) /* grid 8*/
{
for(m=6;m<=8;m++)
{
for(n=3;n<=5;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
if( i>=6 && i<=8 && j>=6 && j<=8) /* grid 9*/
{
for(m=6;m<=8;m++)
{
for(n=6;n<=8;n++)
{
if(i != m && j != n)
{
if(a[i][j] == a[m][n])
{
return 0;
}
}
}
}
return 1;
}
return 0;
}
Your program exits after inserting a value in the matrix. After setting the value of a position in Line 41: a[i][j] = x;, you need to increment your i or j accordingly and then call goto incr;.
PS.: Learn to use simple printf() statements, they are great debuggers.

Pointers Binary Tree Maze Solver in C

I need to create a Robot Simulator programmed in C. The Robot has to find the Exit of a 2d labirinth using a Recursive Backtracker algorithm, i understood how does this algorithm work but i don't know how to implement it. I Think i can use a Binary Tree using Pointers but i don't know how to do this, can you try to explain it to me?
This is the program that i've created, now the Robot is entering a loop because of the method that changes direction
#ifdef __unix__
#include <unistd.h>
#elif defined _WIN32
#include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void goUp();
void goDown();
void goLeft();
void goRight();
typedef struct robot {
int direction;
bool is_moving;
}robot;
typedef struct room {
robot robot;
bool is_robot;
int obstacle;
}room;
room Room[20][20];
int r = 12;
int c = 10;
void generation(room matrix[20][20])
{
srand(time(NULL));
int x,i,j;
x=0;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
matrix[i][j].is_robot=false;
x=rand()%100+1;
if(x==1||x==50||x==100)
{
matrix[i][j].obstacle=1;
}
else
{
matrix[i][j].obstacle=0;
}
}
}
}
void print_matrix(room matrix[20][20])
{
int i,j;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
if(matrix[i][j].obstacle==0)
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf(" ");
}
}
else
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf("o");
}
}
}
printf("\n");
}
}
bool changeDirection(room Room[20][20],int i,int j)
{
if(Room[i][j].robot.direction == 1)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 2;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 2)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 1;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 3)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 4;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
if(Room[i][j].robot.direction == 4)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 3;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
}
void goRight()
{
c=c+1;
Room[r][c].robot.direction=1;
Room[r][c].is_robot=true;
Room[r][c-1].is_robot=false;
}
void goLeft()
{
c=c-1;
Room[r][c].robot.direction=2;
Room[r][c].is_robot=true;
Room[r][c+1].is_robot=false;
}
void goUp()
{
r=r-1;
Room[r][c].robot.direction=3;
Room[r][c].is_robot=true;
Room[r+1][c].is_robot=false;
}
void goDown()
{
r=r+1;
Room[r][c].robot.direction=4;
Room[r][c].is_robot=true;
Room[r-1][c].is_robot=false;
}
int main()
{
generation(Room);
Room[r][c].robot.direction = 1;
Room[r][c].robot.is_moving = true;
Room[r][c].is_robot = true;
do
{
Room[r][c].robot.is_moving = true;
if (Room[r][c].robot.direction == 1 && Room[r][c].robot.is_moving == true) // destra
{
if(Room[r][c +1].obstacle == 1 || c+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goRight();
}
}
if (Room[r][c].robot.direction == 2 && Room[r][c].robot.is_moving == true) // sinistra
{
if(Room[r][c -1].obstacle == 1 || c-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goLeft();
}
}
if (Room[r][c].robot.direction == 3 && Room[r][c].robot.is_moving == true) // su
{
if(Room[r-1][c].obstacle == 1 || r-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goUp();
}
}
if (Room[r][c].robot.direction == 4 && Room[r][c].robot.is_moving == true) // giu
{
if(Room[r+1][c].obstacle == 1 || r+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goDown();
}
}
print_matrix(Room);
sleep(0.1);
system("cls");
}
while(1);
print_matrix(Room);
}
I'm having a hard time understanding how a binary tree would be useful in finding a path in a labyrinth (maybe it's used to represent the labyrinth?) but maybe I'm blind. I would simply make a 2d int array and let 0 mean the position is blocked (there's a wall there or something) and 1 mean it's open (you can move there). The brute force backtrack procedure, going off orthogonal movement (left, right, up, down) would be:
f(x,y){
// you found the place your want to go to
if (x,y) is (destinationX,destinationY)
return true
block the position (x,y) // i.e. mark current position as visited
if there is an open spot at (x,y-1) AND f(x,y-1)
return true
if there is an open spot at (x,y+1) AND f(x,y+1)
return true
if there is an open spot at (x-1,y) AND f(x-1,y)
return true
if there is an open spot at (x+1,y) AND f(x+1,y)
return true
return false
}
Suppose you had the labyrinth looking like:
"+" is where you start ([1][1])
"-" is your destination ([3][1])
"#" is a blocked region
===========
|#|#|#|#|#|
|#|+| |#|#|
|#|#| |#|#|
|#|-| | |#|
|#|#|#|#|#|
===========
Using the above idea I have:
#include <stdio.h>
#define width 5
#define height 5
// print maze
void print(char arr[][width]){
for (int i = 0; i < 2*width+1; i++) printf("=");
printf("\n");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("|%c",arr[i][j]);
}
printf("|\n");
}
for (int i = 0; i < 2*width+1; i++) printf("=");
}
// starting from (x,y) to (destX,destY)
int path(int arr[][width],int x,int y,int destX,int destY,char toDest[][width]){
if (x==destX && y==destY) {
toDest[y][x] = '*';
print(toDest);
return 1;
}
// mark current position as visited
arr[y][x] = 0;
toDest[y][x] = '*';
// left
if (arr[y][x-1] && path(arr,x-1,y,destX,destY,toDest))
return 1;
// right
if (arr[y][x+1] && path(arr,x+1,y,destX,destY,toDest))
return 1;
// up
if (arr[y-1][x] && path(arr,x,y-1,destX,destY,toDest))
return 1;
// down
if (arr[y+1][x] && path(arr,x,y+1,destX,destY,toDest))
return 1;
return 0;
}
int main () {
// use this to store path
// and then print it out if found
char toDest[height][width] = {
{'#','#','#','#','#'},
{'#',' ',' ','#','#'},
{'#','#',' ','#','#'},
{'#',' ',' ',' ','#'},
{'#','#','#','#','#'}
};
// 0 -> position is blocked
// 1 -> position is open
int maze[height][width] = {
{0,0,0,0,0},
{0,1,1,0,0},
{0,0,1,0,0},
{0,1,1,1,0},
{0,0,0,0,0}
};
path(maze,1,1,1,3,toDest);
}
Output:
===========
|#|#|#|#|#|
|#|*|*|#|#|
|#|#|*|#|#|
|#|*|*| |#|
|#|#|#|#|#|
===========
In output the path is designated by the *s

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

Resources