Understanding the logic behind a piece of C code - c

I would love if you guys could explain to me why the following piece of recursive code doesn't print the word 'test'. Thanks in advance.
void drawTetriminosEachPosition(int **tetriminos, char **dBoard, int **tBoard, int i){
char c;
char **dBoard2;
if(tetriminos[i] == '\0')
{
return;
}
else
{
dBoard2 = dBoard;
DrawTetrimino(tBoard, tetriminos[i], dBoard, i+65);
}
i++;
return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
ft_putstr("test");
if(checkChar(tBoard,tetriminos[i]))
{
dBoard = dBoard2;
return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
}
}

Statements after a return are never executed. Since the first
return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
does not depend on any condition, the following code is not executed.

When control reaches return ... it simply returns and next lines are not executed. Maybe you missed some logic in between?
As of now you can delete this part it doesn't matter
ft_putstr("test");
if(checkChar(tBoard,tetriminos[i]))
{
dBoard = dBoard2;
return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
}

Related

Run a function and check if another function is already executed using C

Using C, I want to run one function based on another. I need to check if a specific function is executed. if yes, then I want this function to execute as well when called, otherwise not.
I am reading some text from a file. in the first function, I want to read them and print them. now in the second function, I need a condition, that if the first function is executed, then run this as well. otherwise, do nothing.
How can I do that?
EDIT
NOTE: THIS IS THE COMPLETE SOLUTION. AFTER THE QUESTION WAS ANSWERED.
My code is here:
#include <stdio.h>
static int already_run = 0;
void Reading_Function(FILE **rf)
{
already_run = 1;
*rf=fopen("file.txt","r");
if(rf==NULL)
{
printf("Error in file openning.");
return 0;
}
char first [120];
fscanf(*rf,"%s",first);
printf("Value: %s", first);
}
// this is the second function
void Second_Function(FILE *rf)
{
if (already_run)
{
char second [50];
fscanf(rf,"%s",second);
printf("Value: %s", second);
}
else
return;
}
int main()
{
char t;
FILE *rf;
while(scanf("%c", &t)==1)
{
switch(t)
{
case 'f' :
Reading_Function(&rf);
break;
case 's' :
Second_Function(rf);
break;
}
}
return 0;
}
Let me know if the question is not clear. Thanks.
The comments above already answer your question. Just to keep things simple, here is what the code would look like:
static int already_run = 0;
void Reading_Function(FILE *rf) {
already_run = 1;
// ...
}
void Second_Function(FILE *rf) {
if (already_run) {
// ...
} else {
// ...
}
}
That said, if what you're trying to do is only have people call Second_Function but have the stuff in First_Function run the first time Second_Function is called, a better way to do this is:
void Second_Function(FILE *rf) {
static int already_run = 0;
if (!already_run) {
already_run = 1;
// Initialization code goes here. You can even split it out
// into a second function if you want, in which case you would
// just invoke that function here.
}
// ...
}
That way you don't have any global variables to worry about.
Of course, both methods break down if your code is multi-threaded; in that case, you should use a once (like pthread_once_t, call_once, InitOnceExecuteOnce, or something which abstracts the different APIs away for portability).

Mysterious change of value in pointer vector

As homework I have to implement a function that receives two vectors of pointers. It should compare the values contained in the memory address pointed by these pointers and return TRUE or FALSE if they are all the same or not.
For this I have created this function:
tBoolean comparePointerVector(int *v1[], int *v2[]) {
int i;
tBoolean status = TRUE;
for (i=0;i<MAX_DELIVERIES;i++) {
if(*v1[i]!=*v2[i]) {
status = FALSE;
break;
}
}
return status;
}
The method compiles fine but always crashes in the first iteration. Investigating the problem I have found a very strange phenomena. Adding the next code before entering the for loop, the printed results for both lines are different, which is very surprising for me:
printf("value %d\n ",*v1[0]);
printf("value %d\n ",*v1[0]);
The first line prints correctly the value pointed by v1[0], but the second line prints the memory address. How is this possible that the they don't print the same?
Besides this why this code seems to break my program?
*v1[i]!=*v2[i]
I ask here in the same question because I think both questions are related.
EDIT:
Definition of MAX_DELIVERIES in a file called data.h
#define MAX_DELIVERIES 50
Calling the function:
tBoolean pd_equals(tProductDeliveries pd1, tProductDeliveries pd2){
//For maintenability and better understading this method contains several 'return' statements.
if(pd1.poductID!=pd2.poductID) {
return FALSE;
} else if(pd1.totalPurchases!=pd2.totalPurchases) {
return FALSE;
} else if(pd1.totalSales!=pd2.totalSales) {
return FALSE;
} else if(pd1.total!=pd2.total) {
return FALSE;
} else if(comparePointerVector(pd1.sales, pd2.sales) != TRUE) {
return FALSE;
} else if(comparePointerVector(pd1.purchases, pd2.purchases) != TRUE) {
return FALSE;
}
return TRUE;
}
Calling the pd_equals method:
pd_getProductDeliveries(deliveries, 123, &pd1);
if(pd_equals(pd1, pd1)==TRUE) {
printf("\n\t-> OK\n");
passedTest[0]++;
} else {
printf("\n\t-> FAIL.\n");
}
Thanks everybody for your answers. I got it fixed but now I am even more puzzled.
I just have removed the system("PAUSE"); I had between the two printf and now both print exactly the same. I am sorry I didn't post it in my code but I thought it was totally irrelevant.
Now my next question would be: What in the world is the system("PAUSE") doing that messes up the memory?
I think the issue is caused by the comparison if(*v1[i]!=*v2[i]). It must be
v1[i] != v2[i] or *(v1+i) != *(v2+i)

C : strchr pointer value doesn't change

I'm trying to recursively search for a substring in a string using C program. I wrote the following piece of code. The issue I'm facing is that, the ptr value, though it prints the correct value(using puts in the beginning of while), while usage its value is not changed! It uses the previous ptr value. I found this out using gdb. I couldn't figure out the cause of this. Kindly guide me to solve this issue. Thanks in advance.
void main()
{
char buf[10]="hello",*ptr;
char findc[10]="lo";
int len,i,lenf,k,l,flag=0;
lenf=strlen(findc);
l=0,k=1;
ptr=strchr(buf,findc[l]);
while(ptr!=NULL)
{
puts(ptr);
l++;
for(i=l;i<(lenf);i++,k++)
{
if(ptr[k] != findc[i])
{
flag=1;
break;
}
}
if(flag==1)
{
l=0;k=1;
ptr=strchr((ptr+1),findc[l]);
if(ptr==NULL)
{
puts("String not found");
break;
}
}
else
{
puts("String found");
break;
}
}
}
It was a very simple mistake!
We'll have to reset the flag variable in the beginning of the while loop. This would solve the issue.
Thanks!

How do you use a string array in a conditional statement in C?

I want to use a string array in an if statement to test whether the input string matches any of the strings in the array.
So far this is what I've tried:
void checkForError(char input[50])
{
const char *input2[]={"print","loadStarter","terminate()"};
if(input != input2)
{
printf("Error:Incorrect method '%s'.\n",input);
}
else
{
abort();
}
}
And if I were to enter something in the array like "print" it would end up showing me:
Error:Incorrect method 'print'.
but when I try something not listed in the array like "g" it repeats the error message nonstop.
I was thinking perhaps something like this could work:
void checkForError(char input)
{
if(strcmp(input,"print"))!=0 || strcmp(input,"loadStarter"))!=0 || strcmp(input,"terminate()")
{
printf("Error:Incorrect method '%s'.\n");
}
else
{
abort();
}
}
But it turns out that actually doesn't work so what do I do?
You cannot compare strings (usefully) in C using == and !=; you must use library functions such as strcmp instead. See How to compare strings in an "if" statement? for details.
I think a good solution to your question would be to loop around your array, aborting on the first match.
void checkForError(char* input)
{
const char *input2[]={"print","loadStarter","terminate()"};
const int len = sizeof(input2)/sizeof(input2[0]);
for (int i = 0; i < len ;i ++)
{
if (strcmp(input,input2[i]) == 0)
{
//I have matched the string input2[i]
abort();
}
}
// Nothing matched
printf("Not found\n");
}
This would also be easier to extend than any handcoded method.
Also, if you plan on doing a lot with these strings, and you have a limited number of strings, you should probably turn them into some sort of enum. This way you do not have to have strcmp scattered everywhere, and you can use a standard switch statement.
a better method would be to have a return value then have your error message depend on return value.
// return 1 when string is OK, 0 otherwise:
int checkForError(const char* input)
{
if(!strcmp(input,"print")) || !strcmp(input,"loadStarter")0 || !strcmp(input,"terminate()")
{
return 1;
}
else
{
return 0;
}
}
Your second thought is correct, you should not compare the strings using == operator, anyway, I'm not sure whether the rest is a typo or not, but it should be like that:
void checkForError(char * input)
// ^ note the * (pointer)
{
if(strcmp(input,"print")!=0 || strcmp(input,"loadStarter")!=0 || strcmp(input,"terminate()") != 0)
// you forgot brackets
{
printf("Error:Incorrect method '%s'.\n", input);
// ^ you forgot the "input" parameter
}
else
{
abort();
}
}

Function that searches for difference between members of an array

I need to write a function that will return true if it has found a difference between members of an array.
My code is:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
I have to implement it with pointers.
The code above does not work(logically).
Can anybody help?
UPDATE:
I have changed my code to the following:
int func1(int *str)
{
int i,temp=0;
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
What is the problem with the new code?
This looks like homework to me, so I don't want to spoil the fun but one thing about C I'd like to mention: having a pointer to some array doesn't tell you anything about the size of the array. So your function will need to take a pointer and a second size_t argument (or maybe a pointer to the last element of the array).
Your function only takes in a single array pointer, that seems like one too few for a comparison.
You must add an argument that specifies the lengths of the arrays, or implement some kind of "policy" that e.g. terminates the arrays using a specific value.
You should also look into using the standard memcmp() function.
I don't understand the question (It's unclear what you're trying to achieve)...
As others have already said, there's no boundary checking on your array, which is wrong...
Here's some other feedback on your code:
// func1 - consider giving functions a meaningful name, it helps people to
// understand what the function is supposed to be doing....
// In this instance, it might have been helpful to identify what the expected
// return values / inputs of the function are...
int func1(int *str)
{
int i;
// Start a counter at 0, loop (adding 1) while
// the current value of the counter is less than, the value held in the
// array so, {1,2,3,4,0,7} Would terminate on the 0
// This: {1,20,7,14,0,7} Would also terminate on the 0
// This seems wrong, but again, it's unclear what you're trying to do here.
for(i=0;i<*(str+i);i++) {
// If the current element of the array
// is the same as the next element of the array
if(*(str+i) == *(str+i+1))
{
// return 1 - two numbers next to each other in the
// array are the same?
return 1;
}
}
// Either: The array contained a digit less than the counter,
// Or: It didn't contain two numbers that were the same next to each other.
// This seems a bit wrong?!?
return 0;
}
Your question could be improved (to get a more useful answer), if you showed what inputs you were expecting to return what return values.
Based on this 'I will need to write a function that will return true if its found diffrence between members of array.'
In pseudo code, it seems like you would want:
// Loop, checking we don't overflow. No point checking the last element as
// there's nothing after it to check...
for (count = 0 to arraysize -1) {
// If the current element != the next element, we've found a difference?!?
if(arrayElement[count] != arrayElement[count+1) {
return true
}
}
return false
UPDATE:
In your new code...
// You're still assuming the size of 'str'
int func1(int *str)
{
int i,temp=0;
// Loop while i < 9, i.e. 9 times.
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
// Maybe it should be (temp == 10-1), but I don't know where the
// 10 comes from...
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
This:
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
if( temp == 10 )
{
return 1;
}
}
Could be:
// return 0 (FALSE) on first difference
if(*(str+i) != *(str+i+1))
{
return 0;
}
If you changed the return 0 at the end of your function to return 1

Resources