How to use fork() to iterate/search through a 3D/multi dimension int array - c

Hi guys I'm trying to get some practice out using fork() and with multi dimention arrays.
so i'm trying to tell my program to go through a 3D array where I assigned it at specific locations a certain number and to search through the whole array for that specific number and give me back where it found it.
now I want to use fork() just for practice sake for this. the compiler is giving me a bunch of errors related to both the array itself and the fork()
this what i got so far:
int i,j,k;
int this[100][100][100];
int charlie; //charlie is what i called the result of the a iteration
this[30][2][4]=23;
this[20][1][3]=23;
this[80][19][90]=23;
void ChildProcess()
{
printf("child\n");
for (i=50;i<75;i++)
{
for(j=50;j<75;j++)
{
for(k=50;k<75;k++)
{
charlie=this[i][j][k];
if(charlie==23)
{
printf("i=%d,j=%d,k=%d",i,j,k);
}
}
}
}
}
void ParentProcess()
{
printf("parent\n");
for (i=0;i<50;i++)
{
for(j=0;j<50;j++)
{
for(k=0;k<50;k++)
{
charlie=this[i][j][k];
if(charlie==23)
{
printf("i=%d,j=%d,k=%d",i,j,k);
}
}
}
}
}
void ChildProcess()
{
printf("child2\n");
for (i=75;i<100;i++)
{
for(j=75;j<100;j++)
{
for(k=75;k<100;k++)
{
charlie=this[i][j][k];
if(charlie==23)
{
printf("i=%d,j=%d,k=%d",i,j,k);
}
}
}
}
}
int main()
{
int pid=fork();
printf ("this is the pid %d\n",pid);
if(pid!=0)
{
ParentProcess();
}
else
{
ChildProcess();
}
int pid2=fork();
if (pid==0)
{
ChildProcess2();
}
}
one of the errors it gave me was:
s.c:7:1: warning: data definition has no type or storage class [enabled by default] this[30][2][4]=23;
and
s.c:5:5: note: previous declaration of ‘this’ was here int this[100][100][100];
these 2 errors keep popping up non stop.
to be honest I'm not sure what it means since i didnt reclare it or smt

Related

How to solve the recursive algorithm stack overflow in a maze program?

I have a simple program to solve the maze. But an error is reported: stack overflow. How can I solve the stack overflow?
In my code, 1 represents the wall, 0 represents the path that can be taken, and $ represents the end. (1,2) is the starting point.
This is my code:
#include<stdio.h>
#include<windows.h>
void ShowMaze(char szMaze[][24],int nCount)
{
for(int i=0;i<nCount;i++)
{
printf("%s\r\n",szMaze[i]);
}
}
void Maze(char szMaze[][24],int x,int y)
{
if(szMaze[x][y]=='$')
{
printf("Congratulations!\r\n");
system("pause");
exit(0);
}
if (szMaze[x+1][y]=='$'||szMaze[x+1][y]=='0')
{
Maze(szMaze,x+1,y);
}
if (szMaze[x][y+1]=='$'||szMaze[x][y+1]=='0')
{
Maze(szMaze,x,y+1);
}
if (szMaze[x-1][y]=='$'||szMaze[x-1][y]=='0')
{
Maze(szMaze,x-1,y);
}
if (szMaze[x][y-1]=='$'||szMaze[x][y-1]=='0')
{
Maze(szMaze,x,y-1);
}
return;
}
int main()
{
char szMaze[][24]={
"11111111111111111111111",
"10111111111111111111111",
"10000000001111111111011",
"11111111011111100001011",
"11111111011111101111011",
"11111111000000000001$11",
"11111111011111101111011",
"11111111011111100000001",
"11111111111111111111111"
};
int nRow=sizeof(szMaze)/sizeof(szMaze[0]);
ShowMaze(szMaze,nRow);
Maze(szMaze,1,2);
system("pause");
return 0
To avoid endless loops you need to mark positions that have already been visited.
Something like:
szMaze[x][y]='2'; // mark position as visited
if (szMaze[x+1][y]=='$'||szMaze[x+1][y]=='0')
{
Maze(szMaze,x+1,y);
}
if (szMaze[x][y+1]=='$'||szMaze[x][y+1]=='0')
{
Maze(szMaze,x,y+1);
}
if (szMaze[x-1][y]=='$'||szMaze[x-1][y]=='0')
{
Maze(szMaze,x-1,y);
}
if (szMaze[x][y-1]=='$'||szMaze[x][y-1]=='0')
{
Maze(szMaze,x,y-1);
}
szMaze[x][y]='0'; // release position
and don't start in the wall! Start like:
Maze(szMaze,1,2); ----> Maze(szMaze,1,1);
Note
Your code don't do any boundary checking. Therefore it will only work when the maze has walls at all boundaries. Having such a requirement is kind of "okay" but I would prefer boundary checking instead.

how to change the program to do the same task without the program crashing?

I have an assignment to produce a program that will compare students answer to the answer key, and display the incorrect answers. The program then produces a report of the students incorrect answers and his final grade. The Program must use arrays and functions.
Currently I am trying to code two functions one to read the students answer file and store it in an array and the other to read answer key file and store it in another array. Then the functions will return both arrays to the main function later to be sent to another function to compare their contents(not yet done).
My problem with this code after pressing F11 to compile and run, i get a blank execution screen and a notification saying that the program has stopped working.
If my code contains a mistake or my approach is incorrect please tell me how to fix it.
note: this is my first semester learning C programming.
Thank you.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
//Modules
char* readstudent()
{
FILE*s_ans;
int i,j;
static char arrs[20];
s_ans=fopen("trial2.txt","r");
if (s_ans == NULL)//check if file can be opened
{
printf("error student");
}
while(!feof(s_ans))
{
for(j=0;j<20;j++)
{
fscanf(s_ans,"%s",arrs[j]);
}
}
printf("ReadStudent\n");
for(i=0;i<20;i++)
{
printf("%d\t %s\n",i+1,arrs[i]);
}
return arrs;
}
char* readcorrect()
{
FILE*c_ans;
int x,i;
static char arrc[20];
c_ans=fopen("CorrectAnswers.txt","r");
if (c_ans == NULL)//check if file can be opened
{
printf("error correct");
}
while(!feof(c_ans))
{
for(x=0;x<20;x++)
{
fscanf(c_ans,"%s",arrc[x]);
}
}
printf("ReadCorrect\n");
for(i=0;i<20;i++)
{
printf("%d\t %s\n",i+1,arrc[i]);
}
return arrc;
}
//Main
int main()
{
int i,j,n,x;
char* as_ans=readstudent();
char* ac_ans=readcorrect();
printf("Main");
for(i=0;i<20;i++)
{
printf("%s",as_ans[i]);
}
return 0;
}

My function (which return an array) works in empty file but does not in active project [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 5 years ago.
I'm creating a program that convert a binary number to a hexadecimal one.
This is my function
int cnt(int num)
{
int cn=0;
while (num!=0)
{
cn++;
num=num/10;
}
return cn;
}
int bintodec(int bin)
{
int cn=cnt(bin),result,a=1,i;
int A=0;
for (i=1;i<=cn;i++)
{
A=A+(bin%10)*(a);
a=a*2;bin=bin/10;
}
return A;
}
int *dectohex(int dec)
{
int cn=cnt(dec),i;
int A[cn];
for (i=1;i<=cn;i++)
{
A[cn-i]=dec%16;
dec=dec/16;
}
return A;
}
This is my caller:
int main()
{
int i,x;
printf("x = ");scanf("%d",&x);
for (i=1;i<=5;i++)
{
if (dectohex(x)[i]<10)
{
printf("\t%d",dectohex(x)[i]);
}
else if (dectohex(x)[i]==10)
{
printf("\tA");
}
else if (dectohex(x)[i]==11)
{
printf("\tB");
}
else if (dectohex(x)[i]==12)
{
printf("\tC");
}
else if (dectohex(x)[i]==13)
{
printf("\tD");
}
else if (dectohex(x)[i]==14)
{
printf("\tE");
}
else if (dectohex(x)[i]==15)
{
printf("\tF");
}
}
return 0;
}
It worked well together in an empty file, no error when built, and it printed correct results. But just when I add them to my project, errors appear everywhere I called the function dectohex() like in this image building logs. Did I do something wrong???
Your function does not return an array . It returns a pointer. The pointer points into an array which stops existing when the function returns. When you try to read through the pointer in the calling code, this causes undefined behaviour.
You need to fix your code so that you do not try to access arrays after they have been destroyed.

Function casts itself c, after it has been casted twice

I've got a university project where I have to write a database of workers. I decided to use dynamic array of structures:
struct data
{
char id[50];
char name[50];
char surname[50];
char account_num[50];
double net_pension,taxed_pension;
};
int main()
{
int current_size=0;
struct data *database;//creating a table
database=(struct data*)malloc(1*sizeof(struct data));//memory allocation
menu(database);//running menu
return 0;
}
function menu
void menu(struct data *database)
{
int current_size=1;
int input=0;
char inpt[512];
do
{
printf("Input function or input help for list of avaible commands \n");
fgets(inpt,511,stdin);
input=mod_input(inpt);
if(input==404)
{
printf("Function does not exist \n");
}
else if(input==1)
{
print_result(database,current_size);
}
else if(input==2)
{
add_element(database,&current_size);
}
else if(input==3)
{
modify_element(database,current_size);
}
else if(input==4)
{
sort_table(database, current_size);
}
else if(input==5)
{
search(database,current_size);
}
else if(input==6)
{
hilfe();
}
else if(input==7)
{
search_by_col(database,current_size);
}
input=8;
}
while(input!=0);
}
decides what we want to do, for example writing "add" will start my problematic function, which is supposed to add new records
void add_element(struct data *database,int *size)
{
int subflag=0;
char inpt[50];
int place=((*size)-1);
int pass=(*size);
printf("%i",pass);
if((*size)!=1)
{
modify_element(database,(*size));
}
do
{
printf("Input unical ID \n");
fgets(inpt,50,stdin);
if(does_exist(inpt,database,pass)==1)
{
subflag=1;
strncpy(database[place].id,inpt,50);
}
else
{
printf("ID exists");
}
}
while(subflag==0);
subflag=0;
do
{
printf("Input name \n");
fgets(inpt,50,stdin);
if(is_word(inpt)==1)
{
subflag=1;
strcpy(database[place].name,inpt);
}
}
while(subflag==0);
subflag=0;
do
{
printf("Input surname \n");
fgets(inpt,50,stdin);
if(is_word(inpt)==1)
{
subflag=1;
strcpy(database[place].surname,inpt);
}
}
while(subflag==0);
subflag=0;
do
{
printf("Input account number \n");
fgets(inpt,50,stdin);
if(is_accnum(inpt)==1)
{
subflag=1;
strcpy(database[place].account_num,inpt);
}
}
while(subflag==0);
subflag=0;
do
{
printf("Input net gain \n");
fgets(inpt,50,stdin);
if(is_num(inpt)==true)
{
printf("%d",atof(inpt));
subflag=1;
database[place].net_pension=atof(inpt);
}
}
while(subflag==0);
subflag=0;
do
{
printf("Input taxed gain \n");
fgets(inpt,50,stdin);
if(is_num(inpt)==true)
{
subflag=1;
database[place].taxed_pension=atof(inpt);
}
}
while(subflag==0);
printf("record added \n");
if((*size)==1)
(*size)++;
}
function modify_size reallocs memory, does_exist ensures, that id's are unique, is acc_num, num and word checks input for given rules. They all work perfectly when you use function first time. But after you try to add second one "record added" does not display and function add runs from the beginning. I ahve no idea why. That is the main problem. Secondary one is menu, because when you input "print" it runs add_element. Code that converts input is:
int mod_input(char function[])
{
printf(function);
if(strcmp(function,"modify")==1)
return 3;
else if(strcmp(function,"sort")==1)
return 4;
else if(strcmp(function,"search")==1)
return 5;
else if(strcmp(function,"help")==1)
return 6;
else if(strcmp(function,"add")==1)
return 2;
else if(strcmp(function,"print")==1)
return 1;
else if(strcmp(function,"search_by_column")==1)
return 7;
return 404;
}
Thank you in advance for help. Also I know that some parts could be done better, but for now, I try to just force it to work.
whole programme
lab3.c and header
Intuitively, what you need to do is pass around a pointer to a pointer to your array, not just a pointer to it. And that's what BLUEPIXY was trying to get at in a comment.
The problem is that if you do x = realloc(y, new_size), there's no guarantee that x will be equal to y.
In particular, database = realloc(database, new_size) inside a subroutine may leave the subroutine with a different value for database than the one passed in as an argument. The caller still has the old value for database.
The results are undefined, and may include worse than what you got.
What you want is something like
struct data *datap;
struct data **database = &datap;
*database = malloc(sizeof(struct data))
With corresponding changes all the way down - basically pass database, and set *database = realloc(...) when you get to that stage.
Also, make sure you update *size appropriately at the same time.

Longest Common Subsequence-Segmentation fault

I have to write a program to determine the longest common sub sequence.
Input:
The first argument will be a file that contains two strings per line, semicolon delimited. You can assume that there is only one unique subsequence per test case. e.g.
XMJYAUZ;MZJAWXU
Output:
The longest common subsequence. Ensure that there are no trailing empty spaces on each line you print. e.g.
MJAU
I am using Dev C++ .. And it is compiling Fine!...But this question is a programming challenge and when i submit my answer it's showing me a segmentation fault!
I have written the following code and i am getting a Segmentation Fault where am i wrong?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str1[100],str2[100];
int len1;
int len2;
void printLCS(char b[len1][len2],char str1[],int i,int j)
{
if(i==0 || j==0)
return;
if(b[i][j]=='c')
{
printLCS(b,str1,i-1,j-1);
printf("%c",str1[i-1]);
}
else if(b[i][j]=='l')
printLCS(b,str1,i,j-1);
else
printLCS(b,str1,i-1,j);
}
void Seq(char str1[],char str2[])
{
int i,j;
len1=strlen(str1);
len2=strlen(str2);
int LCS[len1+1][len2+1];
char b[len1][len2];
for(i=0;i<=len1;i++)
{
LCS[i][0]=0;
}
for(j=0;j<=len2;j++)
{
LCS[0][j]=0;
}
for(i=1;i<=len1;i++)
{
for(j=1;j<=len2;j++)
{
if(str1[i-1]==str2[j-1])
{
LCS[i][j]=1+LCS[i-1][j-1];
b[i][j]='c';
}
else if(LCS[i-1][j]>=LCS[i][j-1])
{
LCS[i][j]=LCS[i-1][j];
b[i][j]='u';
}
else
{
LCS[i][j]=LCS[i][j-1];
b[i][j]='l';
}
}
}
printLCS(b,str1,len1,len2);
}
int main(int argc,char *argv[])
{
if(argc!=2)
{
printf("Invalid Number of Arguments:\n");
exit(0);
}
FILE *fp;
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("File can't be opened:\n");
exit(0);
}
char c;
c=fgetc(fp);
while(c!=EOF)
{
int k=0;
if(c=='\n')
c=fgetc(fp);
while(c!=';')
{
str1[k]=c;
k++;
c=fgetc(fp);
}
str1[k]='\0';
c=fgetc(fp);
k=0;
while(c!=EOF && c!='\n')
{
str2[k]=c;
k++;
c=fgetc(fp);
}
str2[k]='\0';
Seq(str1,str2);
printf("\n");
if(c==EOF)
{
break;
}
else
c=fgetc(fp);
}
return 0;
}
I dont know system of this site but;
i compiled with no error,
and result was true.
You didnt close file. Maybe memory leak etc. didnt allowed by site.
And, dont use global variables, unless you dont know another solution
this usage is very very bad! ISO C90 forbids this, anyway
int len1;
int len2;
void printLCS(char b[len1][len2]...
good luck.
If you've got access to a Mac or Linux system, there's a fantastic tool called valgrind which can help you track down these kinds of errors: basically it runs your program in a virtual machine and monitors what it reads and writes to memory.
Whilst I can't compile your code, I'm pretty suspicious about this for loop:
for(i=1;i<=len1;i++)
{
for(j=1;j<=len2;j++)
{
if(str1[i-1]==str2[j-1])
{
LCS[i][j]=1+LCS[i-1][j-1];
b[i][j]='c';
}
else if(LCS[i-1][j]>=LCS[i][j-1])
{
LCS[i][j]=LCS[i-1][j];
b[i][j]='u';
}
else
{
LCS[i][j]=LCS[i][j-1];
b[i][j]='l';
}
}
}
Arrays in C and C++ start at 0, so the maximum offset you're interested in is probably strlen - 1. Try changing your for loops to
for(i=1;i<len1;i++)
{
for(j=1;j<len2;j++)
{
...
}
}

Resources