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)
Related
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).
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));
}
I am trying to create a function will return the value located in the struct. My issue is trying to figure out what I can return by the function if theInfo = NULL?
Below is what I have created so far. Is this possible to do?
int getTime(struct * theInfo){
if(theInfo != NULL){
return theInfo->waitTime;
}
else{
printf("getTime Patron is nonexistent\n");
return(thePatron);
}
}
You need to return two pieces of information - the number, and an indication of whether or not that number is valid. One way to do it is changing the signature of the function to indicate whether or not it returned anything, and in case when it does, stick that value in a variable. Here is an example of how you can do it:
// This function returns 1 or 0.
// 1 indicates success; 0 indicates failure
// If your compiler is up to C99 standard, use "bool" instead of "int" below
int getTime(struct * theInfo, int *result) {
if(theInfo != NULL){
*result = theInfo->waitTime;
return 1;
} else{
// result stays unchanged
return 0;
}
}
Now you can use this new function like this:
int res;
if (getTime(&myInfo, &res)) {
printf("getTime returned %d\n", res);
} else {
printf("getTime Patron is nonexistent\n");
}
A less general alternative can be used when you do not need to return a full range of numbers. For example, if the valid time returned by your function is always positive, you could adopt a convention that uses negative numbers to indicate that there was an error. This approach is also valid, but it relies more on a convention, so a reader of your code would need to look through your function documentation to see what is going on.
You could pass a pointer and return a boolean value indicating success:
bool getTime(MyStruct* info, int* time) {
if (info) {
*time = info->waitTime;
return true;
}
*time = 0;
return false;
}
Then somewhere you would just call:
int time;
if (!getTime(info, &time)) {
// TODO: retrieval of time failed
}
Just return -1. I am sure that wait time is always positive.
So return -1 if it is NULL and then check for -1
else{
printf("getTime Patron is nonexistent\n");
return -1;
}
void someFunc() {
//...
int wtime = getTime(astruct);
if (wtime == -1)
// error
//...
}
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!
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