C Battleship Game Linked List print_node function - c

I've been working on a battleship program in C for a class and I am having trouble with my print_node function returning the values from my head node (currentState, ship_type, charInput etc.). Each time I run it, it compiles however it always outputs "0". I'm hoping a second set of eyes could help me figure this out. Thank you, and forgive me for the messy code.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#define SIZE 10
typedef struct Node{
char currentState;
char ship_type[20];
char charInput;
int intInput;
struct Node* next;
}Node;
char** initialization(){
int i, j, k, row, col;
char **board = (char**)malloc(sizeof(char*)*SIZE);
for (i = 0; i < SIZE; i++){
board[i] = (char*)malloc(sizeof(char)*SIZE);
}
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
board[i][j] = '-';
}
}
//place the first ship
//the direction of placement is hard coded
//you can change it if you want
bool placed1 = false;
while(placed1 == false){
row = rand()%10;
col = rand()%10;
if(row+1 < 10 && row-1 >= 0){
if((board[row][col] = '-') &&
(board[row+1][col] = '-')){
board[row][col] = 'D';
board[row+1][col] = 'D';
placed1 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-')){
board[row][col] = 'D';
board[row-1][col] = 'D';
placed1 = true;
}
}
}
//place the second ship
bool placed2 = false;
while (placed2 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10) &&
(row-1 >= 0 && row-2 >= 0) &&
(col+1 < 10 && col+2 < 10) &&
(col-1 >= 0 && col-2 >= 0)){
if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-')){
board[row][col] = 'C';
board[row][col+1] = 'C';
board[row][col+2] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-')){
board[row][col] = 'C';
board[row][col-1] = 'C';
board[row][col-2] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-')){
board[row][col] = 'C';
board[row+1][col] = 'C';
board[row+2][col] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-')){
board[row][col] = 'C';
board[row-1][col] = 'C';
board[row-2][col] = 'C';
placed2 = true;
}
}
}
//place the third ship
bool placed3 = false;
while (placed3 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10) &&
(row-1 >= 0 && row-2 >= 0) &&
(col+1 < 10 && col+2 < 10) &&
(col-1 >= 0 && col-2 >= 0)){
if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-')){
board[row][col] = 'S';
board[row][col+1] = 'S';
board[row][col+2] = 'S';
placed3 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-')){
board[row][col] = 'S';
board[row][col-1] = 'S';
board[row][col-2] = 'S';
placed3 = true;
}
else if((board[row][col] =='-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-')){
board[row][col] = 'S';
board[row+1][col] = 'S';
board[row+2][col] = 'S';
placed3 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-')){
board[row][col] = 'S';
board[row-1][col] = 'S';
board[row-2][col] = 'S';
placed3 = true;
}
}
}
bool placed4 = false;
while (placed4 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10 && row+3 < 10) &&
(row-1 >= 0 && row-2 >= 0 && row-3 >= 0) &&
(col+1 < 10 && col+2 < 10 && col+3 < 10) &&
(col-1 >= 0 && col-2 >= 0 && col-3 >= 0)){
if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-') &&
(board[row+3][col] == '-')){
board[row][col] = 'B';
board[row+1][col] = 'B';
board[row+2][col] = 'B';
board[row+3][col] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-') &&
(board[row-3][col] == '-')){
board[row][col] = 'B';
board[row-1][col] = 'B';
board[row-2][col] = 'B';
board[row-3][col] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-') &&
(board[row][col+3] == '-')){
board[row][col] = 'B';
board[row][col+1] = 'B';
board[row][col+2] = 'B';
board[row][col+3] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-') &&
(board[row][col-3] == '-')){
board[row][col] = 'B';
board[row][col-1] = 'B';
board[row][col-2] = 'B';
board[row][col-3] = 'B';
placed4 = true;
}
}
}
bool placed5 = false;
while (placed5 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10 && row+3 < 10 && row+4 < 10) &&
(row-1 >= 0 && row-2 >= 0 && row-3 >= 0 && row-4 >= 0) &&
(col+1 < 10 && col+2 < 10 && col+3 < 10 && col+4 < 10) &&
(col-1 >= 0 && col-2 >= 0 && col-3 >= 0 && col-4 >= 0)){
if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-') &&
(board[row+3][col] == '-') &&
(board[row+4][col] == '-')){
board[row][col] = 'R';
board[row+1][col] = 'R';
board[row+2][col] = 'R';
board[row+3][col] = 'R';
board[row+4][col] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-') &&
(board[row-3][col] == '-') &&
(board[row-4][col] == '-')){
board[row][col] = 'R';
board[row-1][col] = 'R';
board[row-2][col] = 'R';
board[row-3][col] = 'R';
board[row-4][col] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-') &&
(board[row][col+3] == '-') &&
(board[row][col+4] == '-')){
board[row][col] = 'R';
board[row][col+1] = 'R';
board[row][col+2] = 'R';
board[row][col+3] = 'R';
board[row][col+4] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-') &&
(board[row][col-3] == '-') &&
(board[row][col-4] == '-')){
board[row][col] = 'R';
board[row][col-1] = 'R';
board[row][col-2] = 'R';
board[row][col-3] = 'R';
board[row][col-4] = 'R';
placed5 = true;
}
}
}
return board;
}
void update_state(char* state, char ** board, char character, int col){
int row;
char shipType[20];
row = character % 65;
if(board[row][col] == '-'){
strcpy(state, "MISS");
}
else{
strcpy(state, "HIT!");
/* add code to change the board to indicate
* that shot hit , for example you could change
* the corresponding letter back to '-'.
* but before this, you need to record the letter
* and corresponding ship type.
*/ //COMPLETED
char shipChar = board[row][col];
if(shipChar == 'R'){
strcpy(shipType,"Carrier");
printf("%s", shipType);
}
else if(shipChar == 'B'){
strcpy(shipType,"Battleship");
printf("%s", shipType);
}
else if(shipChar == 'S'){
strcpy(shipType,"Submarine");
printf("%s", shipType);
}
else if(shipChar == 'C'){
strcpy(shipType,"Cruiser");
printf("%s", shipType);
}
else if(shipChar == 'D'){
strcpy(shipType,"Destroyer");
printf("%s", shipType);
}
printf("%c", shipChar);
board[row][col] = '-'; //set target coordinates to '-'
}
/* add code to update temp node's attributes (i.e
* hit or miss, ship type, then insert the temp node
* the node into the linked list.
* You may need to write the insert node function
* (you can refer to the insert node function in lab5
* handout )
*/
struct Node *head, *tail;
head = tail = NULL;
insert_node(&head, &tail, col, row, *state, shipType);
print_node(head);
//check if game is over //completed
int m = 0;
int k, l;
for(k = 0; k < SIZE; k++){
for(l = 0; l < SIZE; l++){
if(board[k][l] == '-'){
m++;
if(m >= 100){
strcpy(state, "GAME OVER!");
}
}
}
}
}
int accept_input(char * c, int * i){
bool flag = true;
do{
printf("Enter a letter A-J and number 0-9 ex. B4 - enter Z0 to end\n");
int size = scanf(" %c%d", c, i);
if(size != 2){
printf("INVALID INPUT\n");
continue;
}
*c = toupper(*c);
if(*c == 'Z' && *i == 0)
break;
if (*c < 65 || *c > 74)
printf("INVALID INPUT\n");
else if (*i <0 || *i >9)
printf("INVALID INPUT\n");
else
flag = false;
}while(flag);
}
/*
char currentState;
char ship_type;
*/
void insert_node(struct Node **h, struct Node **t, int x, char y, char* state, char shipTyp){
//create new node with value given by int x, y
struct Node *temp;
if ((temp = (struct Node *)malloc(sizeof(struct Node))) == NULL){
printf("Node Allocation Failed \n");
exit(1);
}
//space for node obtained, copy values into node
temp->charInput = y; //store user character input
temp->intInput = x; //store user number input
temp->currentState = state; //store state
temp->ship_type[20] = shipTyp; //store shipType
temp->next = NULL;
if (*h == NULL){
//list is empty if so
*h = *t = temp;
}
else{ //list isnt empty, use *t to add node at the end
(*t)->next = temp;
*t = (*t)->next;
}
}
//will be converted to a write to file function
void print_node(struct Node *h){
if(h == NULL){
printf("The list is empty.\n");
}
else{
printf("Values in the list are: \n");
while(h != NULL) {
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
h = h->next;
}
}
}
void display_state(char* state, char** board){
int i, j;
printf("\n**** %s ****\n", state);
printf(" 0 1 2 3 4 5 6 7 8 9\n");
for (i = 0; i < SIZE; i++){
printf("%c ", 65+i);
for (j = 0; j < SIZE; j++){
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int teardown(char ** board){
int i;
for(i = 0; i < SIZE; i++)
free(board[i]);
free(board);
/* add code below to traverse the linkded list
* you should create a log file name "log.txt"
* traverse each node in the linked list, and
* write the information in each node into "log.txt"
* Each line should follow this format:
* Fired at A1. Hit - Carrier.
* Fired at C2. Miss.
* You may refer to the print_list function in lab5
* handout.
* In addition, remember to free the nodes of the
* linked list.
*/
return 0;
}
int main(void){
//
void print_node(struct Node*);
void insert_node(struct Node**, struct Node**, int, char, char*, char);
srand(time(NULL));
char** board;
char state[] = "GAME START";
char flag[] = "GAME OVER!";
char character;
int integer;
/* declare a linked list below*/ //COMPLETED
//struct Node* head = NULL;
//struct Node* second = NULL;
//head = (struct Node*)malloc(sizeof(struct Node));
//second = (struct Node*)malloc(sizeof(struct Node));
board = initialization();
do{
display_state(state, board);
if(display_state)
/*modify the accept_input function
* accept input function should return
* a temp node, which stores the current valid
* input (i.e. character and letter)
*/
accept_input(&character, &integer);
if(character == 'Z' && integer == 0)
break;
/*modify the update_state function
* update_state function should accept
* the head node of linked list and the
* temp node
*/
update_state(state, board, character, integer);
} while((character != 'Z' || integer != 0) && strcmp(state, flag) );
/*modify the teardown function
* tear_down function should accept
* a head node of linked list
*/
teardown(board);
return 0;
}
//modularize insertNode, etc. inito own functions

Try this
void print_node(struct Node *h) {
if(h != null){
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
print_node(h->next);
}
}

I noticed you call your print function in update_state, which means you are storing to the file every move.
number 1, you need to append to the file and not write
change:
fPTR = fopen("log.txt", "w");
to:
fPTR = fopen("log.txt", "a");
And change your write function to:
//will be converted to a write to file function
void print_node(struct Node *h, FILE *fPTR){
printf("got this far");
if (h == NULL) {
printf("THE LIST IS EMPTY\n");
}
else{
printf("\nThis move was:\n");
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
printf("%d\n", h->intInput);
printf("%s\n", h->currentState);
fprintf(fPTR, "Fired at %c%d. %s - %s. \n", h->charInput, h->intInput, h->currentState, h->ship_type);
fclose(fPTR);
}
}
This is assuming your linkedist head is created correctly
EDIT: This code gets the last move played and adds it to the file, you will have to delete the file whenever you start a new game.

Related

My If-statements seem to be ignored even though my variables look fine in the debugger

I just started learning C (I'm an absolute beginner) and I'm trying to make a program that translates Roman numbers to Arabic and vice versa.
If I were to type "IX" my program should give me a "9" as an output but instead I get a "1". I tried to find the issue on my own using the debugger and I can see my program entering the first If-Statement
if (userString[localIndex] == 'I')
but then it skips the inner If-Statement
else if (userString[++localIndex] == 'X') {
ARABIC_NUM += 9;
localIndex++;
}
I'm not sure why this is happening. If I type "IV" my program outputs a "4" which is the correct answer but if I type "IVIV" my programs once again outputs a lonely "4" and ignores the rest of my input.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define NOT_A_NUMBER 0
#define IS_ROMAN 1
#define IS_ARABIC 2
int ARABIC_NUM = 0;
int findStringLength(char* userString) {
int stringLength = 0;
size_t index = 0;
while (userString[index] != '\0')
{
if (userString[index] != '\0') {
stringLength++;
index++;
}
}
return stringLength;
}
void resetString(char* userString)
{
size_t stringLength = findStringLength(userString);
for (size_t index = 0; index < stringLength; index++)
{
userString[index] = '\0';
}
}
void printString(char* userString)
{
size_t stringLength = findStringLength(userString);
for (size_t index = 0; index < stringLength; index++)
{
if (userString[index] != '\0')
printf("~%zu:%c~ ", index, userString[index]);
else
printf("Null character");
}
}
bool ifEnd(char* numberInput, size_t counter) {
bool userEnd = false;
for (size_t index = 0; index < counter; index++)
{
if ((numberInput[index - 2] == 'E' && numberInput[index - 1] == 'N' && numberInput[index] == 'D')) {
userEnd = true;
}
}
return userEnd;
}
int isNumTrue(char userChar) {
int isRoman = NOT_A_NUMBER;
int isArabic = NOT_A_NUMBER;
if (userChar == 'I' || userChar == 'V' || userChar == 'X' ||
userChar == 'L' || userChar == 'C' || userChar == 'D' || userChar == 'M') {
isRoman = IS_ROMAN;
return isRoman;
}
else if (userChar == '0' || userChar == '1' || userChar == '2' || userChar == '3' || userChar == '4' || userChar == '5' || userChar == '6' || userChar == '7' || userChar == '8' || userChar == '9') {
isArabic = IS_ARABIC;
return isArabic;
}
else {
return NOT_A_NUMBER;
}
}
void convertToArabic(char* userString, size_t counter) {
for (size_t localIndex = 0; userString[localIndex] != '\0'; localIndex++) {
// printf("[ %c%s]", userString[localIndex], "-o ");
if (userString[localIndex] == 'I') {
if (userString[++localIndex] == 'V') {
printf("Made it in");
ARABIC_NUM += 4;
localIndex++;
}
else if (userString[++localIndex] == 'X') {
ARABIC_NUM += 9;
localIndex++;
}
else {
ARABIC_NUM += 1;
}
}
else if (userString[localIndex] == 'V') {
ARABIC_NUM += 5;
}
else if (userString[localIndex] == 'X') {
if (userString[localIndex++] == 'L') {
ARABIC_NUM += 40;
localIndex++;
}
else if (userString[localIndex++] == 'C') {
ARABIC_NUM += 90;
localIndex++;
}
else {
ARABIC_NUM += 10;
}
}
else if (userString[localIndex] == 'L') {
ARABIC_NUM += 50;
}
else if (userString[localIndex] == 'C') {
if (userString[localIndex++] == 'D') {
ARABIC_NUM += 400;
localIndex++;
}
else if (userString[localIndex++] == 'M') {
ARABIC_NUM += 900;
localIndex++;
}
else {
ARABIC_NUM += 100;
}
}
else if (userString[localIndex] == 'D') {
ARABIC_NUM += 500;
}
else if (userString[localIndex] == 'M') {
ARABIC_NUM += 1000;
}
else {
printf("Switch default. You shouldn't be seeing this");
}
/* else
{
printf("[ %c%s]", userString[localIndex],"-x ");
}*/
}
printf("%s%d%s", "\n Number was :", ARABIC_NUM, "\n");
}
bool convertToRoman(char* userString, char* romanStringHolder, size_t counter) {
bool isValid = true;
int arabicNum = atoi(userString);
char repetitionLimit = '\0';
for (size_t index = 0; arabicNum != 0; index++) {
/* if ((isNumTrue(userString[index]) == IS_ARABIC || userString[index] == '\n') && index < counter)
{
printf("[ %c%s]", userString[index], "-o ");
}*/
if (arabicNum >= 4000) {
do {
if (romanStringHolder[index - 2] == romanStringHolder[index - 1] == romanStringHolder[index]) {
repetitionLimit = romanStringHolder[index - 2];
}
if (arabicNum / 1000000 >= 1)//&& repetitionLimit != 'M')
{
romanStringHolder[index] = 'M';
arabicNum -= 1000000;
}
else if (arabicNum / 900000 >= 1)// && repetitionLimit != 'M')
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'M';
arabicNum -= 900000;
}
else if (arabicNum / 500000 >= 1)// && repetitionLimit != 'D')
{
romanStringHolder[index] = 'D';
arabicNum -= 500000;
}
else if (arabicNum / 400000 >= 1)//&& repetitionLimit != 'D')
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'D';
arabicNum -= 400000;
}
else if (arabicNum / 100000 >= 1)// && repetitionLimit != 'C')
{
romanStringHolder[index] = 'C';
arabicNum -= 100000;
}
else if (arabicNum / 90000 >= 1)//&& repetitionLimit != 'C')
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'C';
arabicNum -= 90000;
}
else if (arabicNum / 50000 >= 1)// && repetitionLimit != 'L')
{
romanStringHolder[index] = 'L';
arabicNum -= 50000;
}
else if (arabicNum / 40000 >= 1)// && repetitionLimit != 'L')
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'L';
arabicNum -= 40000;
}
else if (arabicNum / 10000 >= 1)//&& repetitionLimit != 'X')
{
romanStringHolder[index] = 'X';
arabicNum -= 10000;
}
else if (arabicNum / 9000 >= 1)// && repetitionLimit != 'X')
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'X';
arabicNum -= 9000;
}
else if (arabicNum / 5000 >= 1)//&& repetitionLimit != 'V')
{
romanStringHolder[index] = 'V';
arabicNum -= 5000;
}
else if (arabicNum / 4000 >= 1)//&& repetitionLimit != 'I')
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'V';
arabicNum -= 4000;
}
else if (arabicNum / 1000 >= 1)// && repetitionLimit != 'I')
{
romanStringHolder[index] = 'I';
arabicNum -= 1000;
}
index++;
} while (arabicNum >= 4000);
romanStringHolder[index] = '_';
index++;
}
if (arabicNum <= 3999) {
if (arabicNum / 1000 >= 1)
{
romanStringHolder[index] = 'M';
arabicNum -= 1000;
}
if (arabicNum / 900 >= 1)
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'M';
arabicNum -= 900;
}
else if (arabicNum / 500 >= 1)
{
romanStringHolder[index] = 'D';
arabicNum -= 500;
}
else if (arabicNum / 400 >= 1)
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'D';
arabicNum -= 400;
}
else if (arabicNum / 100 >= 1)
{
romanStringHolder[index] = 'C';
arabicNum -= 100;
}
else if (arabicNum / 90 >= 1)
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'C';
arabicNum -= 90;
}
else if (arabicNum / 50 >= 1)
{
romanStringHolder[index] = 'L';
arabicNum -= 50;
}
else if (arabicNum / 40 >= 1)
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'L';
arabicNum -= 40;
}
else if (arabicNum / 10 >= 1)
{
romanStringHolder[index] = 'X';
arabicNum -= 10;
}
else if (arabicNum / 9 >= 1)
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'X';
arabicNum -= 9;
}
else if (arabicNum / 5 >= 1)
{
romanStringHolder[index] = 'V';
arabicNum -= 5;
}
else if (arabicNum / 4 >= 1)
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'V';
arabicNum -= 4;
}
else if (arabicNum / 1 >= 1)
{
romanStringHolder[index] = 'I';
arabicNum -= 1;
}
}
}
if (romanStringHolder > 3999999)
printf("\n");
return isValid;
}
int findNumSystem(char* userString, char* toRomanString) {
//printf(" -%zu and %d-", counter, findStringLength(userString));
size_t counter = findStringLength(userString);
int romanNumAmount = 0;
int arabicNumAmount = 0;
int notNumAmount = 0;
for (size_t localIndex = 0; localIndex < counter; localIndex++) {
if (isNumTrue(userString[localIndex]) == IS_ROMAN || ((isNumTrue(userString[localIndex - 1]) == IS_ROMAN) && (userString[localIndex] == '\n')))
{
printf("[ %c%s]", userString[localIndex], "-R ");
romanNumAmount++;
if (romanNumAmount == (findStringLength(userString) - 1)) {
printf("\nAll Numbers are Roman");
convertToArabic(userString, counter);
break;
}
}
else if (isNumTrue(userString[localIndex]) == IS_ARABIC || ((isNumTrue(userString[localIndex - 1]) == IS_ARABIC) && (userString[localIndex] == '\n')))
{
printf("[ %c%s]", userString[localIndex], "-A ");
arabicNumAmount++;
if (arabicNumAmount == (findStringLength(userString) - 1))
{
printf("\nAll numbers are Arabic");
convertToRoman(userString, toRomanString, counter);
printString(toRomanString);
break;
}
}
else if (isNumTrue(userString[localIndex]) == NOT_A_NUMBER)
{
printf("[ %c%s]", userString[localIndex], "-X ");
notNumAmount++;
if (notNumAmount == (findStringLength(userString))) {
printf("\nNone of the characters is a number of either system");
}
}
}
}
#define LENGTH 1000u
int main() {
typedef char user_Input_Stream;
char lol = '\0';
user_Input_Stream arabToRomanString[LENGTH] = { '\0' };
user_Input_Stream numberInput[LENGTH] = { '\0' };
size_t counter = 0;
bool userEnd = false;
while ((lol != EOF) && (userEnd == false))
{
counter = 0;
printString(&numberInput);
resetString(&numberInput);
resetString(&arabToRomanString);
counter = 0;
printString(&numberInput);
ARABIC_NUM = 0;
printf("\n\n||Beta version, remember to not mix number systems yet||\n");
//Repeats until variable lol countains EOF or until boolean holds a true value
while ((lol != EOF) && (lol != '\n') && (userEnd == false))
{
//gets characters, assigns string with them. Gets rid of newline and stores string in array in uppercase
lol = getchar();
numberInput[counter] = toupper(lol);
userEnd = ifEnd(numberInput, counter);
counter++;
}
//TESTING Travels through String and outputs cells contents. Also, sets boolean to True if user writes END
for (size_t i = 0; i < counter; i++) {
if (numberInput[i] == '\n')
{
lol = '\\';
numberInput[i] = toupper(lol);
}
// printf("| [%zu] = %c |", i, numberInput[i]);
}
findNumSystem(numberInput, arabToRomanString);
printf("\n");
}
printf("\n");
return 0;
}
Does anyone have an idea of what the issue could be? (ARABIC_NUM is a global variable, the name is to make it easier for me to find for now.)
Just in case this might help somebody else, here's the solution I came up with using some of the pointers people in the comment section gave me. It was fairly simple:
I was under the impression that expressions within if-statements don't affect any variables they reference, but in reality they do.
For example: if(userString[localIndex] == 'I' && userString[localIndex++] == 'X')
In the line above, I was expecting the program to check both the current index and the next upcoming index, which it did but the expression userString[localIndex++] within the if-statement also permanently incremented my localIndex variable when I wasn't expecting that change to exist outside of the if-statement's parenthesis. So, my program would check the wrong indexes after the first comparison was made and thus why it gave me the wrong output.
To solve this, I created the variable nextIndex and used it to store the value localIndex +1 meaning it will always represent the index after localIndex. So, It now works as intended.
Below is what my program looks like now. (I moved around the if and if-else statements for better readability but the only changed that solved my predicament was the addition of nextIndex)
void convertToArabic(char* userString, size_t counter) {
size_t nextIndex = 0;
for (size_t localIndex = 0; localIndex < findStringLength(userString); localIndex++) {
// printf("[ %c%s]", userString[localIndex], "-o ");
nextIndex = localIndex+1;
if (userString[localIndex] == 'M') {
ARABIC_NUM += 1000;
}
else if (userString[localIndex] == 'C' && userString[nextIndex] == 'M') {
ARABIC_NUM += 900;
localIndex++;
}
else if (userString[localIndex] == 'D') {
ARABIC_NUM += 500;
}
else if (userString[localIndex] == 'C' && userString[nextIndex] == 'D') {
ARABIC_NUM += 400;
localIndex++;
}
else if(userString[localIndex] == 'C'){
ARABIC_NUM += 100;
}
else if (userString[localIndex] == 'X' && userString[nextIndex] == 'C') {
ARABIC_NUM += 90;
localIndex++;
}
else if (userString[localIndex] == 'L') {
ARABIC_NUM += 50;
}
else if (userString[localIndex] == 'X' && userString[nextIndex] == 'L'){
ARABIC_NUM += 40;
localIndex++;
}
else if (userString[localIndex] == 'X') {
ARABIC_NUM += 10;
}
else if ((userString[localIndex] == 'I') && (userString[nextIndex] == 'X')) {
//localIndex--;
ARABIC_NUM += 9;
localIndex++;
}
else if (userString[localIndex] == 'V') {
ARABIC_NUM += 5;
}
else if ((userString[localIndex] == 'I') && (userString[nextIndex] == 'V')) {
//localIndex--;
printf("Made it in");
ARABIC_NUM += 4;
localIndex++;
}
else if (userString[localIndex] == 'I') {
ARABIC_NUM += 1;
}
/* else
{
printf("[ %c%s]", userString[localIndex],"-x ");
}*/
}
printf("%s%d%s", "\n Number was :", ARABIC_NUM, "\n");
}

Find index of word in string

I want to write a function which will find index of word in string.
For example if string is
This is word.
my function for string "word" should return number 3.
Note: functions from string.h library and auxiliary strings are not allowed.
How could I do this in C?
I can't think of a solution better than this (though there might be better ones).
#include <stdio.h>
int main() {
char word[] = "This is a word";
int flag = 0, space = 0, pos = -1;
for (int i = 0; word[i] != '\0'; i++) {
if (flag == 1) {
break;
}
for (int j = 0; word[j] != '\0'; j++) {
if (flag == 1) {
break;
}
else if (word[j+1] == '\0' || word[j+2] == '\0' || word[j+3] == '\0') {
break;
}
else {
if (word[j] == 'w' && word[j+1] == 'o' && word[j+2] == 'r' && word[j+3] == 'd') {
flag = 1;
pos = j;
}
}
}
}
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] == ' ' || word[i] == '!' || word[i] == '#') {// And many more symbols
fchars++;
}
else {
break;
}
}
if (flag == 1 && pos-1 > 0 && word[pos-1] == ' ') {
for (int i = 0; i < pos; i++) {
if (word[i] == ' ') {
space++;
}
}
printf("Found at position = %i\n", space+1-fchars);
}
else {
printf("Not found!\n");
}
}
You can split the sentence by space to get the words and then match each word in the sentence with the word you want to match
Please check this modified code:
#include<stdio.h>
int main()
{
char word[] = "word";
char string[100];
gets(string);
int curWordStart = -1;
int curWordEnd = -1;
int wordCount = 0;
int i = 0;
for (i = 0; string[i] != '\0'; i++)
{
if (string[i] == ' ')
{
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
curWordStart = -1;
curWordEnd = -1;
}
else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
{
if (curWordStart == -1) {
curWordStart = i;
}
curWordEnd = i;
}
}
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
return 0;
}
It will print each position of the searched word in the sentence. If you want to just print the first one, you can easily modify it.
Here are steps to follow:
you must specify precisely what is a word in the string.
measure the length len of the word to search
define an int index = 1
in a loop, using a pointer p starting at the beginning of the string:
advance p past all word delimiters (spaces, punctuation or non letters?)
if p is at end of string return 0 (not found).
measure the length len1 of the current word in the string
if len1 == len and all bytes are identical to those of the word, return index
otherwise skip the word by advancing p by len1, increment index and continue the loop.
Here is an implementation:
#include <stddef.h>
int isletter(char c) {
/* assuming ASCII */
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
int word_index(const char *str, const char *word) {
const char *p = str;
size_t len, len1, i;
int index = 1;
for (len = 0; word[len]; len++)
continue;
for (;;) {
while (!is_letter(*p))
p++;
if (*p == '\0')
return 0;
for (len1 = 0; is_letter(p[len1]); len1++)
continue;
if (len1 == len) {
for (i = 0; i < len && p[i] == word[i]; i++)
continue;
if (i == len)
return index;
}
p += len1;
index++;
}
}

bin node search in map

I try to search in a map I created. Each cell have 3 branches. When A is the closest, B after and C is the farthest. I'm trying to find the shortest route.
It is possible, for instance, that b->c->c->a is closer than a->a->a->a->a.
What should I do?
gag *pathfinder(gag *root, int choice)
{
if (root == NULL)
{
printf_s("the map didnt exits.");
getchar();
exit(1);
}
if (choice == root->index)
{
printf_s("(%d,%d)", root->x, root->y);
return root;
}
if (choice != root->index)
if (root->A != NULL)
{
if (root->A->index != NULL && root->A->index == choice)
;
else
{
pathfinder(root->A, choice);
}
}
else if (choice != root->index)
if (root->B != NULL)
{
if (root->B->index != NULL && root->B->index == choice)
; // printf_s("(%d,%d)->", root->B->x, root->B->y);
else
{
pathfinder(root->B, choice);
}
}
else if (choice != root->index)
if (root->C != NULL)
{
if (root->C->index != NULL && root->C->index == choice)
; //
printf_s("(%d,%d)->", root->C->x, root->C->y);
else
{
pathfinder(root->C, choice);
printf_s("(%d,%d)->", root->C->x, root->C->y);
}
}
}
gag* path(gag *map, gag* tree, int len) {
char temp = map->index;
gag* hold;
tree->index = temp;
static int c = -1;
int *close;
c++;
(map)->index = 'v'; // Mark as visited.
(map)->entries++;
//go A
if (!map->A || map->A->index == 'v' || map->A->entries == 3)
tree->A = NULL;
else {
hold = malloc(sizeof(gag)*len);
d_p_s(map, hold);
tree->A = path(map->A, hold, len);
}
//go B
if (!map->B || map->B->index == 'v' || map->B->entries == 3)
tree->B = NULL;
else {
hold = malloc(sizeof(gag)*len);
d_p_s(map, hold);
tree->B = path(map->B, hold, len);
}
//go C
if (!map->C || map->C->index == 'v' || map->C->entries == 3)
tree->C = NULL;
else {
hold = malloc(sizeof(gag*)*len);
d_p_s(map, hold);
tree->C = path(map->C, hold, len);
}
map->index = temp;
return tree;
}

GPRMC string is not showing after extracting the data - C

Im working around PIC with GPS module. My GPS modules send NMEA data
$GPRMC,000036.799,V,,,,,0.00,0.00,060180,,,N*40
$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32
$GPGGA,000036.799,,,,,0,0,,,M,,M,,*4A
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPGLL,,,,,000036.799,V,N*78
$GPTXT,01,01,02,ANTSTATUS=OPEN*2B
Here my intention is to extract "GPRMC" data string from the above. I think i've sucessfully took it off the "GPRMC", but the problem is the exracted data string doesnt have GPRMC string. here is the screenshot of my hyperterminal window
Here is my code:
while (1)
{
//memset(gpsdata,0,sizeof(gpsdata));
char c = uartrec2();
if (c == '$')
{
char c1 = uartrec2();
if (c1 == 'G')
{
char c2 = uartrec2();
if (c2 == 'P')
{
char c3 = uartrec2();
if (c3 == 'R')
{
char c4 = uartrec2();
if (c4 == 'M')
{
char c5 = uartrec2();
if (c5 == 'C')
{
for (i = 0 ; i < 100 ; i++)
{
gpsdata[i] = uartrec2();
/* while (gpsdata[i] == '\r' || gpsdata[i] == '\n')
{
break;
} */
if (gpsdata[i] == '\r' ) // Checking for '\r'
{
gpsdata[i] = '\0';
}
}
}
}
}
else
{
printf("Bad GPS data");
}
}
}
}
uart_str(gpsdata);
uart_str("\r\n");
}
The first thing you should do is try to figure out a better way to write this program, this could be
int done;
done = 0;
while (done == 0)
{
const char *string;
int valid;
valid = 1;
string = "$GPRMC";
while ((*string != '\0') && ((valid = (uartec2() == *string)) != 0))
string++;
if (valid != 0)
{
for (int i = 0 ; i < 100 ; ++i)
{
gpsdata[i] = uartec2();
if (gpsdata[i] != '\r')
continue;
gpsdata[i] = '\0';
}
uart_str(gpsdata);
uart_str("\r\n");
}
}
How about just adding it since you know there was it?
if (c5 == 'C')
{
gpsdata[0] = '$';
gpsdata[1] = 'G';
gpsdata[2] = 'P';
gpsdata[3] = 'R';
gpsdata[4] = 'M';
gpsdata[5] = 'C';
for (i = 6 ; i < 100 ; i++)
{
gpsdata[i] = uartrec2();
/* while (gpsdata[i] == '\r' || gpsdata[i] == '\n')
{
break;
} */
if (gpsdata[i] == '\r' ) // Checking for '\r'
{
gpsdata[i] = '\0';
}
}
}

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