How can I have this grid wrap around on all sides? - c

I have an assignment where I need to let the user create the height and width of a grid. Then be able to place "ships" onto that grid at any x and y coordinates. Then you can place a storm on a certain section of that grid to then prompt and see if a storm is overlapped with a ship. I have done that successfully but I can't get the storm to wrap around the grid. For example if the grid is 20x20 and I put a storm that starts on the 20th spot over it should shift to the 1 position on the left side of the grid. Here is that code I have a diagram of what it looks like. (Note there is no physical grid getting printed to the terminal)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ship {
// Declaring variables
char shipName[21];
int x, y, w, h;
char direction;
struct ship *next;
} Ship;
//Declaring head of linked list
Ship *head = NULL;
void newShip(int x, int y, char direction, char *shipName) {
//Adding ships to linked list
Ship *new_ship = (Ship *)malloc(sizeof(Ship));
strcpy(new_ship->shipName, shipName);
new_ship->x = x;
new_ship->y = y;
new_ship->direction = direction;
new_ship->next = head;
head = new_ship;
}
void shipMovement(int time, int w, int h) {
//Moving ships
Ship *current = head;
while (current != NULL) {
if (current->direction = 'U') {
current->y = (current->y + time) % h;
}
else if (current->direction = 'D') {
current->y = (current->y - time + h) % h;
}
else if (current->direction = 'L') {
current->x = (current->x - time + w) % w;
}
else if (current->direction = 'R') {
current->x = (current->x + time) % w;
}
else {
printf("Invalid Direction!\n");
}
current = current->next;
}
}
void checkAffShips(int x, int y, int w, int h, char **affShips, int *numAffShips) {
//Checking if ships are affected by storm
Ship *current = head;
while (current != NULL) {
if (((current->x >= x) && (current->x < x + w)) && ((current->y >= y) && (current->y < y + h))) {
// add shipName to list of affected ships
affShips[*numAffShips] = (char *)malloc(sizeof(char) * 21);
strcpy(affShips[(*numAffShips)++], current->shipName);
}
current = current->next;
}
}
//Main Function------------------------------------------------------------------
int main() {
int w, h;
int stormWidth, stormHeight;
scanf("%d %d", &w, &h);
char userInput;
//Looping through commands
while (scanf(" %c", &userInput) != 4) {
if (userInput == '1') {
int x, y;
char direction[21], shipName[21];
scanf("%d %d %s %s", &x, &y, direction, shipName);
newShip(x, y, direction[0], shipName);
} else if (userInput == '2') {
int time;
scanf("%d", &time);
shipMovement(time, w, h);
} else if (userInput == '3') {
int x, y, w, h;
scanf("%d %d %d %d", &x, &y, &w, &h);
char *affShips[1000];
int numAffShips = 0;
checkAffShips(x, y, w, h, affShips, &numAffShips);
printf("%d\n", numAffShips);
for (int i = 0; i < numAffShips; i++) {
printf("%s\n", affShips[i]);
free(affShips[i]);
}
} else if (userInput == '4') {
break;
}
else {
printf("Invalid Input!\n");
}
}
return 0;
}
Here is the documentation:
(https://i.stack.imgur.com/K28We.png)
I've tried a bunch of different stuff so maybe I just didn't do something right in my attempts but I'm sure someone can help figure this out.

Your test for the affected ships is wrong. In your example, if you have a storm of size 2 in the bottom right corner (19, 19), a ship in the top left corner (0, 0) isn't caught, because 0 is not in the range [19, 21).
One way to fix this is to move the point you want to test into the "extended range" if it lies below the starting point of the storm. (The "extended range" is the range that does not wrap and so extends to two times the width of the board.)
So to test whether a one-dimensional point lies in a cyclic range, you could use a function like this:
int in_cyclic_range(int n, int lower, int width, int wrap)
{
if (n < lower) n += wrap;
return (n < lower + width);
}
If you now test n in the whole range from [0, 20) on the storm at 19 of width 2, with in_cyclic_range(n, 19, 2, 20), you will get hits at locations 19 and 0.

In order to test if a ship is affected by a storm, you need the storm position and dimensions, the ship position and the grid dimensions.
In your code, you use w, and h for the grid dimensions and a new set of variables w and h for the storm dimensions in the local scope of if (userInput == '3') { ... }. This is confusing and makes the grid dimensions inaccessible from this part of the code. You should use stormWidth and stormHeight for the storm dimensions and pass both these and the grid dimensions to the checkAffShips function.
The test in checkAffShips for the wrapped coordinate system is more complicated than what you wrote to take into account the wrapped parts of the storm area: as many as 3 extra rectangles.
Also note these issues:
using explicit names for the grid and storm dimensions would help avoid confusion.
the w and h fields in the Ship structure are unused.
reading strings with scanf should be protected by specifying the maximum number of characters to store into the destination array before the null terminator.
newShip should not use strcpy directly as the shipName argument could be longer than the destination array.
you should check the return value of scanf() to detect invalid or missing input.
if (current->direction = 'U') sets current->direction and evaluates to true. You should use == instead of =
the array of shipnames affShips should be allocated by checkAffShips.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ship {
char shipName[21];
int x, y;
char direction;
struct ship *next;
} Ship;
//Declaring head of linked list
Ship *head = NULL;
/* string copy function with size limitation */
void mystrcpy(char *dest, size_t size, const char *src) {
while (size > 1) {
*dest++ = *src++;
size--;
}
if (size > 0)
*dest = '\0';
}
void newShip(int x, int y, char direction, const char *shipName) {
//Adding ship to linked list
Ship *new_ship = (Ship *)malloc(sizeof(*new_ship));
if (new_ship) {
mystrcpy(new_ship->shipName, sizeof new_ship->shipName, shipName);
new_ship->x = x;
new_ship->y = y;
new_ship->direction = direction;
new_ship->next = head;
head = new_ship;
}
}
void shipMovement(int time, int w, int h) {
//Moving ships
for (Ship *current = head; current != NULL; current = current->next) {
if (current->direction == 'U') {
current->y = (current->y + time) % h;
} else
if (current->direction == 'D') {
current->y = (current->y + h - time % h) % h;
} else
if (current->direction == 'L') {
current->x = (current->x + w - time % w) % w;
} else
if (current->direction == 'R') {
current->x = (current->x + time) % w;
} else {
printf("%s: invalid Direction '%c'!\n",
current->shipName, current->direction);
}
}
}
char **checkAffShips(int stormX, int stormY, int stormWidth, int stormHeight,
int gridWidth, int gridHeight,
int *pnumAffShips)
{
char **affShips = NULL;
int numAffShips = 0;
for (Ship *current = head; current != NULL; current = current->next) {
int x = current->x;
int y = current->y;
//Checking if ship is affected by storm
if (((x >= stormX && x < stormX + stormWidth) ||
(stormX + stormWidth > gridWidth && x < (stormX + stormWidth) % gridWidth)) &&
((y >= stormY && y < stormY + stormHeight) ||
(stormY + stormHeight > gridHeight && y < (stormY + stormHeight) % gridHeight)))
{
// add shipName to list of affected ships
affShips = realloc(affShips, sizeof(*affShips) * (numAffShips + 1));
affShips[numAffShips++] = strdup(current->shipName);
}
}
*pnumAffShips = numAffShips;
return affShips;
}
//Main Function------------------------------------------------------------------
int main() {
int gridWidth, gridHeight;
if (scanf("%d %d", &gridWidth, &gridHeight) != 2)
return 1;
char userInput;
//Looping through commands
while (scanf(" %c", &userInput) == 1) {
if (userInput == '1') {
int x, y;
char direction[21], shipName[21];
if (scanf("%d %d %20s %20s", &x, &y, direction, shipName) != 4)
return 1;
newShip(x, y, direction[0], shipName);
} else
if (userInput == '2') {
int time;
if (scanf("%d", &time) != 1)
return 1;
shipMovement(time, gridWidth, gridHeight);
} else
if (userInput == '3') {
int x, y, stormWidth, stormHeight;
if (scanf("%d %d %d %d", &x, &y, &stormWidth, &stormHeight) != 4)
return 1;
char **affShips;
int numAffShips = 0;
affShips = checkAffShips(x, y, stormWidth, stormHeight,
gridWidth, gridHeight, &numAffShips);
printf("%d\n", numAffShips);
for (int i = 0; i < numAffShips; i++) {
printf("%s\n", affShips[i]);
free(affShips[i]);
}
free(affShips);
} else
if (userInput == '4') {
break;
} else {
printf("Invalid Input!\n");
}
}
return 0;
}

Related

process exits prematurely C programming

there is a part where the program asks the user to enter Y or N and then loops beck when I choose N or else it will end the while loop and continue. when I choose the Y for the first time the program works fine but when I choose N and then Y after my program exits even if it does not encounter the return keyword from the main
and it exits with a garbage return value. It stops at system("cls");. Can anyone tell me what's wrong with this code. Note:
Statistician is an integer pointer type that I created with typedef. And, I've also declared the SIZE variable in the survey.h file
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "survey.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
SIZE = 10;
int c, count = 0, item = 0;
Statistician arr;
float mea, med;
arr = (int*)calloc(10, sizeof(int));
printf("Enter 10 answers\n");
while(count < SIZE) // this is the while loop that loops until Y is chosen by the user in the add function
{
while(item > 9 || item < 1)
{
scanf("%d", &item);
}
++count;
add(arr, &count, &SIZE, item);
item = 0;
}
system("cls");
mea = mean(arr, count);
med = median(arr, count);
printf("mean = %f\n", mea);
printf("median = %f\n", med);
return 0;
}
definition of add() function:
void add(Statistician answer, int *count, int *SIZE, int item)
{
int i, j, temp;
bool swapped;
char choice;
answer[*count - 1] = item;
for(i = 0; i < *count - 1; i++)
{
swapped = false;
for(j = 0; j < *count - i - 1; j++)
{
if(answer[j] > answer[j + 1])
{
temp = answer[j];
answer[j] = answer[j + 1];
answer[j + 1] = temp;
swapped = true;
}
}
if(swapped == false)
break;
}
if(*count == *SIZE)
{
printf("Array is full do you want to compute now?\n");
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
{
choice = toupper(getch());
}
if(toupper(choice) == 'Y') // returns without changing the value of SIZE thus ending the while loop at main
{
return;
}
else if(toupper(choice) == 'N') // adds 10 to SIZE thus continuing the while loop in main and returns
{
printf("add another 10 answers\n");
*SIZE += 10;
realloc(answer, *SIZE);
}
}
return;
}
There are probably other issues (I'm not going to look too closely), but you certainly need to fix:
while(item > 9 || item < 1)
{
scanf("%d", &item);
}
If scanf matches zero items, then that is an infinite loop, with scanf repeatedly returning 0, reading the same data and not changing item. You must always check the value returned by scanf.
This is a serious bug:
realloc(answer, *SIZE);
You don't save the return value so you have lost the allocated memory. Further, you forgot the object size.
In principle you should do
Statistician tmp = realloc(answer, *SIZE * sizeof(int));
if (tmp == NULL)
{
// Error handling
// or just
exit(1);
}
answer = tmp;
However, that doesn't fully help. The problem is that it will only change the value of answer inside the function but not the value of arr in main. In order to change the value of arr you'll have to pass the address of arr to the function. Similar to what you have done with SIZE. BTW: Why do you pass counter as a pointer? You never change it in the function, so it unnecessary to pass a pointer.
Also your current code doesn't initialize choice.
Change
printf("Array is full do you want to compute now?\n");
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
to
printf("Array is full do you want to compute now?\n");
choice = ' ';
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
or better:
printf("Array is full do you want to compute now?\n");
do
{
choice = toupper(getch());
} while(toupper(choice) != 'N' && toupper(choice) != 'Y');
BTW:
Since you have choice = toupper(getch()); you don't need toupper(choice) != 'N'. Simply do choice != 'N'
All that said - why do you want to ask the question inside the function? Your code will be much simpler if you do it in main.
Something like:
int main(void) {
int SIZE = 10;
int c, count = 0, item = 0;
int* arr;
float mea, med;
arr = calloc(10, sizeof(int));
printf("Enter 10 answers\n");
while(count < SIZE)
{
while(item > 9 || item < 1)
{
if (scanf("%d", &item) != 1) exit(1);
}
++count;
add(arr, count, item);
item = 0;
if (count == SIZE)
{
printf("Array is full do you want to compute now?\n");
char choice;
do
{
choice = toupper(getch());
} while(choice != 'N' && choice != 'Y');
if(choice == 'N')
{
printf("add another 10 answers\n");
SIZE += 10;
int* tmp = realloc(arr, SIZE * sizeof *arr);
if (tmp == NULL) exit(1); // or error handling
arr = tmp;
}
}
}
system("cls");
mea = mean(arr, count);
med = median(arr, count);
printf("mean = %f\n", mea);
printf("median = %f\n", med);
return 0;
}
void add(int* answer, int count, int item)
{
int i, j, temp;
bool swapped;
answer[count - 1] = item;
for(i = 0; i < count - 1; i++)
{
swapped = false;
for(j = 0; j < count - i - 1; j++)
{
if(answer[j] > answer[j + 1])
{
temp = answer[j];
answer[j] = answer[j + 1];
answer[j + 1] = temp;
swapped = true;
}
}
if(swapped == false)
break;
}
return;
}

Binary Interpolation Search cannot find the number im looking for (C)

I have an assignment demanding I utilize the algorithm of Binary Interpolation Search in order to find a number and its position in an array, which I'm entering through the keyboard. Unfortunately, while I get no errors, the program returns nothing even though it asks me to enter a number! If you have any idea what might be going wrong it will be helpful!
Here is my code:
#include<stdio.h>
#include<math.h>
int bis(int Array[],int x)
{
int i;
int hitpos;
int left = 0;
int right = sizeof(Array);
int size = right - left + 1;
int next;
int a = x - Array[left];
int b = Array[right]-Array[left];
int c = right - left + 1;
int d = (int)(i*sqrt(size));
next = (size*a/b+1);
do
{
i=0;
size = right - left +1;
if(x >= Array[next])
{
do
{
i = i+1;
right = next + i*sqrt(size);
left = next + (i-1)*sqrt(size);
}
while(x > Array[next + d -1]);
}
else if(x < Array[next])
{
do
{
i = i+1;
right = next -(i-1)*sqrt(size);
left = next - i*sqrt(size);
next = left + (c*a/b);
}
while(x < Array[next - d + 1]);
}
else if(x = Array[next])
{
return next;
}
else
{
return -1;
}
}
while (x != Array[next]);
}
int main()
{
int Array[] = {1,8,10,14,31,55,56,78,87,101};
printf("Please provide a number for binary interpolation search\n");
int x;
scanf("%d", x);
int hit;
hit = bis(Array,x);
if (hit != -1)
{
printf("Element found at index %d", hit);
}
else
printf("Element not found.");
return 0;
}

Split up program with 2 dimensional arrays into Functions (C)

I've written a program in C which allows me to move around in a "room" which is a 2 dimensional array. It works fine, but now I am running into issues when trying to split it up into functions. I might approach it completely wrong as I've only worked in Visual Basic, where stuff like this is much easier.
The void functions with printf also work perfectly fine.
Here's my code:
#include <stdio.h>
void instruction(void) {
printf("Move: W=up, D=right, S=down, A=left an apply with RETURN.\n");
}
void wall(void) {
printf("##### You are in front of a wall. Please move somewhere else! #####\n");
}
int runter(roomxy, y, x, index) {
roomxy[y][x] = 0;
y = y + 1;
if (y>3 || y<0) {
y = y - 1;
wall();
index--;
return (index);
}
return (roomxy[y][x]);
}
void main() {
char c[2];
int steps;
int i;
int j;
int k;
int room[4][4] = { 0 };
int ypos = 0;
int xpos = 0;
room[ypos][xpos] = 1;
for(j=0; j<4; j++) {
for(k=0; k<4; k++) {
printf("%d ", room[j][k]);
}
printf("\n");
}
printf("How many steps do you want to make? (Number from 1 to 50.)\n");
scanf("%d", &steps);
if (steps>0 && steps<51) {
for (i=1; i<=steps; i++) {
instruction();
scanf("%s", c);
if (c[0] == 'S' || c[0] == 's') {
room = runter(room, ypos, xpos, i);
/*room[ypos][xpos] = 0;
ypos = ypos + 1;
if (ypos>3 || ypos<0) {
ypos = ypos - 1;
wall();
i--;
}*/
}
else if (c[0] == 'W' || c[0] == 'w') {
room[ypos][xpos] = 0;
ypos = ypos - 1;
if (ypos>3 || ypos<0) {
ypos = ypos + 1;
wall();
ypos = ypos + 1;
wall();
i--;
}
}
else if (c[0] == 'D' || c[0] == 'd') {
room[ypos][xpos] = 0;
xpos = xpos + 1;
if (xpos>3 || xpos<0) {
xpos = xpos - 1;
wall();
i--;
}
}
else if (c[0] == 'A' || c[0] == 'a') {
room[ypos][xpos] = 0;
xpos = xpos - 1;
if (xpos>3 || xpos<0) {
xpos = xpos + 1;
wall();
i--;
}
}
else {printf("##### ERROR: Only type in W, D, S or A! #####\n"); i--;}
room[ypos][xpos] = 1;
printf("Ihre Position:\n");
for(j=0; j<4; j++) {
for(k=0; k<4; k++) {
printf("%d ", room[j][k]);
}
printf("\n");
}
}
}
else {printf("##### Please enter number from 1 to 50! #####\n");}
}
The error I am getting is "subscripted value is neither array nor pointer nor vector".
I don't know how to move on as I am completely stuck at trying to figure out how functions with arrays work in C.
I've also read about the typedef argument, but I also don't really know how to work with it.
Obviously I am a bloody noob at programming in general.
Thank you guys in advance!
Your source code is muddled, so there are a number of things to fix.
First, change void main() to int main(void). That is just required by the C standard; main must be either int main(void) or int main(int argc, char *argv[]) in normal situations.
Next, you must declare parameter types when you declare a function. int runter(roomxy, y, x, index) is wrong because it fails to say what types the parameters are. Likely, you want either int runter(int roomxy[][4], int y, int x, int index) or int runter(int *roomxy, int y, int x, int index). The former passes the entire array (by way of a pointer to its first subarray) to runter. The latter passes a pointer to a specific element. The first should be used if runter needs to work with multiple elements of the array. The second should be used if runter needs to work with only a specific element. However, using the second form requires additional changes in your program, and it requires use of pointers that you may not have learned about yet, so I am going to omit discussion of that.
Then, it is not clear what you want runter to return. In one place inside the function, you have return (index);. In another, you have return (roomxy[[y][x]);. It is not clear to me whether the index and roomxy[y][x] are two possible values of one kind of thing you want to return or whether they are different kinds of things. If they are the same kind of thing, okay. But if they represent different things, it generally does not make sense for a function to return one or the other.
In any case, return statements do not need parentheses. return index; and return roomxy[y][x] are fine.
Where you call runter, you have room = runter(room, ypos, xpos, i);. This does not make sense because room is an array but runter returns an int. You cannot assign an int to an array. Perhaps you meant room[ypos][xpos] = runter(room, ypos, xpos, 1);. (If so, then it does appear you want runter to work with a single element, so the pointer-to-an-element solution would be better. But you can get the program working and then worry about that.)
I have modified your source. in runter() you are returning int and have catch with room which is pointer(2 dimensional). it's impossible.
Add on to this you should have declare datatype in int runter(roomxy, y, x, index). I have corrected it.
#include <stdio.h>
void instruction(void) {
printf("Move: W=up, D=right, S=down, A=left an apply with RETURN.\n");
}
void wall(void) {
printf("##### You are in front of a wall. Please move somewhere else! #####\n");
}
void runter(int roomxy[][4], int y, int x, int index) {
roomxy[y][x] = 0;
y = y + 1;
if (y>3 || y<0) {
y = y - 1;
wall();
index--;
// return (index);
}
// return (roomxy[y][x]);
}
int main() {
char c[2];
int steps;
int i;
int j;
int k;
int room[4][4] = { 0 };
int ypos = 0;
int xpos = 0;
room[ypos][xpos] = 1;
for(j=0; j<4; j++) {
for(k=0; k<4; k++) {
printf("%d ", room[j][k]);
}
printf("\n");
}
printf("How many steps do you want to make? (Number from 1 to 50.)\n");
scanf("%d", &steps);
if (steps>0 && steps<51) {
for (i=1; i<=steps; i++) {
instruction();
scanf("%s", c);
if (c[0] == 'S' || c[0] == 's') {
/* room[ypos][xpos] = */runter(room, ypos, xpos, i);
room[ypos][xpos] = 0;
ypos = ypos + 1;
if (ypos>3 || ypos<0) {
ypos = ypos - 1;
wall();
i--;
}
}
else if (c[0] == 'W' || c[0] == 'w') {
room[ypos][xpos] = 0;
ypos = ypos - 1;
if (ypos>3 || ypos<0) {
ypos = ypos + 1;
wall();
/* ypos = ypos + 1;
wall();*/
i--;
}
}
else if (c[0] == 'D' || c[0] == 'd') {
room[ypos][xpos] = 0;
xpos = xpos + 1;
if (xpos>3 || xpos<0) {
xpos = xpos - 1;
wall();
i--;
}
}
else if (c[0] == 'A' || c[0] == 'a') {
room[ypos][xpos] = 0;
xpos = xpos - 1;
if (xpos>3 || xpos<0) {
xpos = xpos + 1;
wall();
i--;
}
}
else {printf("##### ERROR: Only type in W, D, S or A! #####\n"); i--;}
room[ypos][xpos] = 1;
printf("Ihre Position:\n");
for(j=0; j<4; j++) {
for(k=0; k<4; k++) {
printf("%d ", room[j][k]);
}
printf("\n");
}
}
}
else {printf("##### Please enter number from 1 to 50! #####\n");}
return 0;
}

Reverse Polish converter

I am trying to make a reverse Polish printer which can perform the following operation-
Inputs:
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))
Outputs:
abc*+
ab+zx+*
at+bac++cd+^*
This is my code:
#include <stdio.h>
#include <string.h>
char pop(int t);
void push(int c, int t);
int main()
{
int z;
scanf("%d", &z);
char *a[100];
int i = 0;
int q = z;
while (q-- > 0)
{
char v[400];
scanf("%s", &v);
int t;
for (t = 0; t < strlen(v); t++) //loop to put the values and signs in the 2 stacks
{
if ((v[t] == '*') || (v[t] == '+') || (v[t] == '-') || (v[t] == '^'))
{
push(v[t], 2);
}
else if (v[t] == ')')
{
int y = pop(2);
push(y, 1);
}
else
{
push(v[t], 1);
}
}
int k = 0;
char c;
while ((c = pop(1)) !='\0') //loop to put elements in the array v
{
if (c != '(')
{
v[k++] = c;
}
}
v[k--] = '\0';
int m;
for (m=0; m != k; m++, k--) //for reversing the string
{
char t = v[m];
v[m] = v[k];
v[k] = t;
}
a[i++] =v;
printf("%s",a[i - 1]);
}
int p;
for (p = 0; p <z ; p++) //printing the elements
printf("%s\n",*a[p]);
return 0;
}
char ac[400];
char as[400];
int ic = 0;
int is = 0;
void push(int c,int t)
{
if (t == 1 && ic != 400)
ac[ic++] = c;
else if (t == 2 && is != 400)
as[is++] = c;
}
char pop(int t)
{
if (t == 1 && ic != 0)
return ac[--ic];
if (t == 2 && is != 0)
return as[--is];
return '\0';
}
But it is not even inputting properly and I am not able to figure out what are the mistakes in this code.Please help to figure out what are the problems.
after inputing the no of test cases i.e.int z and first line if input
it crashes
This is due to the
printf("%s\n",*a[p]);
as BLUEPIXY noticed, *a[p] is a char; but %s expects a char *, thus you need
printf("%s\n", a[p]);
and regarding v is out of scope, the crucial factor is not the scope (visibility), but the storage duration (lifetime) of v - its lifetime ends when execution of the block with which it is associated ends, and the value of a pointer a[i] to it becomes indeterminate; by changing
a[i++] =v;
to
a[i++] = strdup(v);
you can remedy that.

Why I am getting a SIGSEGV error for this program?

I am trying to make a reverse Polish printer on an online coding website which can perform the following operation-
Inputs:
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))
Outputs:
abc*+
ab+zx+*
at+bac++cd+^*
This is my code:
#include <stdio.h>
#include <string.h>
char pop(int t);
void push(int c, int t);
char a[100][400];
int main()
{
int z;
scanf("%d", &z);
int i = 0;
int q = z;
while (q-- > 0)
{
scanf("%s",&a[i][0]);
int t;
for (t = 0; t < strlen(a[i]); t++) //loop to put the values and signs in the 2 stacks
{
if ((a[i][t] == '*') || (a[i][t] == '+') || (a[i][t] == '-') || (a[i][t] == '^'))
{
push(a[i][t], 2);
}
else if (a[i][t] == ')')
{
int y = pop(2);
push(y, 1);
}
else
{
push(a[i][t], 1);
}
}
int k = 0;
char c;
while ((c = pop(1)) !='\0') //loop to put elements in the array v
{
if (c != '(')
{
a[i][k++] = c;
}
}
a[i][k--] = '\0';
int m;
for (m=0; m != k; m++, k--)
{
char t = a[i][m];
a[i][m] = a[i][k];
a[i][k] = t;
}
}
int p;
for (p = 0; p <z ; p++)
printf("%s\n",a[i]);
return 0;
}
char ac[400];
char as[400];
int ic = 0;
int is = 0;
void push(int c,int t)
{
if (t == 1 && ic != 400)
ac[ic++] = c;
else if (t == 2 && is != 400)
as[is++] = c;
}
char pop(int t)
{
if (t == 1 && ic != 0)
return ac[--ic];
if (t == 2 && is != 0)
return as[--is];
return '\0';
}
On compiling this code I am getting a SIGSEGV error.I don't know whats the mistake in this code.Please help
I don't know why you are getting SIGSEGV. However, I see couple of errors in your code.
You are using scanf("%s",&a[i][0]); but i is never changed from its initial value of 0. I suggest changing
while (q-- > 0)
to
for ( i = 0; i < z; ++i )
You are printing a[i] even though you are using p as the for loop index in
for (p = 0; p <z ; p++)
printf("%s\n",a[i]);
That's easily fixed by changing the second line to:
printf("%s\n",a[p]);
In your input, you didn't include the value of z. I hope that is an error in creating the post and that you have the value of z in your input.
With those changes, I don't see any problem in my environment. I tested using gcc 4.7.3. Not sure fixing those will fix the problem in your environment.

Resources