Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've tried to understand this one, but no chance. How it works?
#include <stdio.h>
int tavuk(int i)
{
return (i%3 != 0 ? i + tavuk(--i) : i);
}
void main(void)
{
int *p, array_a[]={5,2,4,7,3};
p = array_a;
printf("%d", tavuk(array_a[*(++p)]));
}
You should attach a debugger to the program, place some breakpoints and step through it one line at a time, so you can watch the code do its magic. Maybe adding additional parenthesis and spaces around illegible expressions could help you as well.
I wrote a step by step explanation of what happens below (read it at your own risk):
p points to the first element in array_a[] after p = array_a;
then ++p is executed and p points to the second element in array_a (and its address is returned to the dereference operator *)
* returns the value (2) of the second field in the array (since ++p returned the address of array_a[1])
now array_a[2] is retrieved and its value (4) is passed into tavuk(...)
inside tavuk(...) (4%3 != 0) evaluates to true
--i is executed (now i = 3)
tavuk(...) is called with 3, inside it (3%3 != 0) evaluates to false and 3 is returned
the decremented i (3) is added to the return value of the second tavuk(...) call (also 3) and 6 is returned
6 is printed to stdout
Initially p points to the beginning of the array array_p.
The statement array_a[*(++p)] can be broken down as follows:
++p ==> increment point to next memory address, in this case address of array_p[1]
*(++p) ==> integer value at this address, in this case 2 or array_p[1]
Therefore, you pass integer value of 2 to the tavuk method.
Upon returning from the method, you would get a value of 5.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
first post here so be gentle. I'm trying execute a recursive binary search. I have tried different variations of code to try to make the function work but i still doesnt.
Here's my code:
bool contained(int x, const int* pBegin, const int* pEnd){
if(x==*pBegin) { //
return pBegin;
}
int size = pEnd - pBegin; //size of the array
int mid= size/2; //the middle of the array
int const* pMid = pBegin + mid; //The address of the element in the middle of the array
if(x>*pMid) //Condition that looks if x is to the left of the array
return contained(x,pMid,pEnd);
else if(x<*pMid) //Condition that looks if x is to the right of the array
return contained(x,pBegin,pMid-1);
}
int main()
{
cout << "Binary search, test: " << endl;
int arr[] = {1,2,3,4,5,7,8,9};
int size = 9;
for(int i=0; i<size; i+=1)
arr[i] = i;
bool find = containedInSortedarray(6, &arr[0], &arr[size]);
cout << "Found " << find << endl;
}
For example here, when i execute my bool-contained function with a premade array and let it search for the value 6, it should eventually come to the conclusion that the element does not exist, yet my output says it does. Have i missed something in my code?
Thanks in advance!
There are a couple of issues with your code:
You never return false.
You return pBegin which is not a bool, (sadly in your case) it is implicitly convertible to one, but not in the way you want it too. Turn on your compiler warnings all the way up - -Wextra -Wall -pedantic -Werror should be the bare minimum, especially if you are a beginner.
Be precise about the interval your function searches in. func(x,a,b) - does it include b? Based on contained(x,pBegin,pMid-1); it seems it does, but in the case of containedInSortedarray(6, &arr[0], &arr[size]); hopefully not.
Dereferencing &arr[size] is UB.
What is the purpose of the for loop in main?
Having the size detached from the array is a disaster waiting to happen. At least use sizeof(arr)/sizeof(arr[0]). Better yet, use std::array or a std::vector.
I would suggest searching [a,b) because it can be easily be divided into [a,mid), [mid,end). That way your mid computation is already correct. You can then call it like containedInSortedarray(x,arr,arr+arr_size)
The base condition should catch the arrays of size 0 and 1 - both can be trivially tested for presence of x.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I made this function that returns the number of digits in an integer:
it works fine when I used ELSE to return the count
int getIndex(int number, int count) { // at first call count is 0
number /= 10;
if (number > 0){
getIndex(number,++count);
}
else{
return ++count;
}
}
but when I first tried to execute without ELSE statement I thought function will be called recursively till IF condition is not met and then only it will encounter the return statement
And function will exit there as integer is returned, but
actually
if the number contains more than one digit, doesn't matter how many time it increase with recursive call it outputs 2
Just curious where as to why I am getting my concept wrong
it works fine when I used ELSE
Actually, the behaviour of the shown program is undefined. If the if branch is entered, then no return statement will be reached, and the behaviour of the program will be undefined.
When you remove the else statement and instead return unconditionally, the behaviour is well defined: The function will always return count + 1 or count + 2 depending on the value of number (which isn't correct).
Consider this, where do you use the value of the recursive function call? Nowhere; you simply discard the value. Would it make sense to return that value to the caller? Yes, it would. If only you returned within the if branch, the behaviour would be correct.
return getIndex(number,++count);
Then it won't matter whether the recursion-terminating branch is within else or not, it will only be executed if the if branch is not executed:
You are missing a return before the recursive call.
By default, it returns 0 (for some compilers).
Edit:
But actually the code should have looked like this:
int getIndex(int number) {
if (number > 0) {
return getIndex(number/10) + 1;
} else {
return 0;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
int f_point(int kek,int *lol) {
*lol *= *lol;
return kek;
}
int main {
int x;
std::cin >> x;
int *adress_of_x = &x;
int a,b = f_point(x,&x); //how does it work?
std::cout << a << LINE_JUMP;
std::cout << b << LINE_JUMP;
}
For example, if I give 2 to program then I will get 0 and 2. Why?
b = f_point(x,&x) in this statement value of first parameter is 2.
Your function is not changing the value of first parameter and returns the same value.
Your are passing first parameter by value so it has no relation with the updated value of x. Variable a is uninitialized, so it is taking a garbage value.
int a,b = f_point(x,&x); //how does it work?
The variable declaration leaves a uninitialized and initializes b from the result of f_point(x,&x);.
Since it's an uninitialized variable, accessing the value of a in the
std::cout << a << LINE_JUMP;
statement leads to undefined behavior of your program. Having an output of 0 is just one of any possibilities (including your fridge explodes unexpectedly or little demons flying out of your nostrils).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Can anyone explain why do I get the result 4 after using
a[]="informatics";
cout<<strchr(a, 't')-(a+3);
Shouldn't I get the result of -4?
Because I subtract a shorter string ("tics") from "ormatics". In my opinion, if I had "ormatics-tics" it would make sense to return a string, orma, not a number at all.
Why is that, I can't find reference of this thing. Also, when I tried the same thing, after I done myself what strchr returns, I got -4:
cout<<" tics"-"ormatics";`
Can someone explain please?
a holds the pointer to the first character of the char array containing "informatics".
strchr(a, 't') returns the pointer to the first "t" (which is the 8th character).
the result is a+7.
so your calculation resolves to:
strchr(a, 't')-(a+3) == (a+7)-(a+3) == 7-3 == 4
Edit:
This answer is a bit misleading as it implies that a is a pointer.
This is wrong! a is an array and not a pointer.
The differences are best explained here: c-faq - Arrays and Pointers
A better wording would be that an array often is used like a pointer, as some operations simply use the address of the first element of the array.
A improved calculation could look like this:
strchr(a, 't')-(a+3) == (&a[0] +7)-(&a[0] +3) == 7-3 == 4
(Thank you Martin Bonner for pointing that out.)
You are doing a Pointer subtraction.
This is what is happening :
So strchr(a, 't')-(a+3) is,
(0+7)-(0+3) => 4
*Considering a to be 0 for simplicity *
Note : When you subtract two pointers, as long as they point into the
same array, the result is the number of elements separating them
Source
" tics"-"ormatics"
substracts two arbitrary const char* pointers. There can't be any prediction made about the difference.
There's absolutely no relation to their actual string contents.
Let me extend your example:
const char a[]="informatics"; // a is an array with 12 elements (inc terminator).
const char* const pa = a; // pa is a pointer to char. Let us say for the sake of
// argument it has value 0x1000
const auto pt = strchr(a,'t') // pt will be a pointer with value 0x1007
const auto ap3 = a+3 // ap3 will be a pointer with value 0x1003
const auto diff = pt - ap3; // diff will be type ptrdiff_t, and given the values
// above, you shouldn't be surprised it has
// value 4.
std::cout<<diff<<std::endl; // Will output "4".
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm studying C++ using a few books, trying to learn SDL along side it. I understand that pointers "point" to a variable's memory address, and that they can be used to "reference" variables. But I don't understand their purpose? And how to use them properly?
I have a few examples from the book (I've added under the code that confuses me):
#include <iostream>
int main(void)
{
char string[6] = "Hello";
char* letter = string;
letter += 3;
OK, so there's a char pointer called 'letter' that points to the memory address of string. Then somehow we use the += operator on the pointer? How? What's going add? What are we adding the 3 to?
*letter = 'p';
And now here we use '*letter' instead of 'letter' - this means it's dereferenced, right? What does this actually DO?
string[4] = '!';
std::cout << string << '\n';
system("PAUSE");
return 0;
}
The rest of the code I understand.
Thanks for any answers!
George
EDIT: so let me get this straight - dereferencing a pointer (e.g. *pointer = 2;) is used to change the value of the variable (or array position, for that matter) when you want to?
EDIT 2: thanks to everybody's answers I almost completely understand the code I used as an example - however, I am still unsure as to the use of '&' (ampersand) in the context of pointers, and how/why they're used.
In this definition
char* letter = string;
letter is set to the address of the first element of character array string.
So *letter has value 'H'.
Let consider for example statement
++letter;
This statement "moves" the pointer to point to the next element of string. That is now the pointer points to the second element of string. Now the value pf *letter is 'e' because letter points to the second element.
Applying three times operator ++ as for example
++letter; ++letter; ++letter;
is equivalent to
letter += 3;
that is the pointer was moved three times and now it points to the second 'l' in string.
This statement
*letter = 'p'
will replace 'l' with 'p' and you will get that string now looks as
"Helpo"
After executing statement
string[4] = '!';
string contains
"Help!"
Instead of
string[4] = '!';
you could write
++letter;
*letter = '!';
Or you could combine these two statements in one statement
*++letter = '!';
EDIT: 'pointer' contains address of an object. When you write *pointer you access directly the object itself so *pointer = 2 change the object pointed by 'pointer'.
Also you should understand that if for example you have
int a[10];
int *p = a;
and let assume that the value of p (the address stored in p) is 4. Then expression ++p or p + 1 means that the pointer was "moved" to the next element of the array. It means that new value of p is not 5. The new value of p is p + sizeof( int ) that is 8 provided that sizeof( int ) is equal to 4.
In your example sizeof( char ) is always equal to 1 according to the C++ Standard.
You need a start from understanding pointers from beginning.
char string[6] = "Hello"; //string an array of 6 characters including null char
char* letter = string; //letter pointer pointing to string array,stores first char address
letter += 3; // Letter pointer in incremented by 3 char. Now it points to 4th char of string
*letter='p'; //replacing 4th char of string by p
cout<<letter; //prints "po";
Notes to help you
What are the barriers to understanding pointers and what can be done to overcome them?
Incrementing a pointer by an integer value (explained with an example):
Suppose you have int* x pointing to memory address 1000, and you increment it by 3: x += 3.
Variable x will now point to memory address 1000 + sizeof(int).
The size of int depends on your compiler; let's assume it is 4 bytes on your system.
So variable x is pointing to memory address 1012 (1000+3*4).
Now, suppose you use x in order to read the value at the memory address pointed by x:
int y = *x;
During runtime, the CPU will read 4 bytes from the memory address pointed by x, and store them into variable y, so that y will then contain the same value as the one stored in address range 1012-1015.
Then somehow we use the += operator on the pointer? How? What's going add? What are we adding the 3 to?
letter is in fact pointing to the first element of the string Hello. By adding 3 to it letter will point to the element 3 of the string (4th element).
And now here we use '*letter' instead of 'letter' - this means it's dereferenced, right? What does this actually DO?
Defreference means you are retrieving the value stored at the location letter points to.
ereferencing a pointer (e.g. *pointer = 2;) is used to change the value of the variable (or array position, for that matter) when you want to?
By doing *pointer = 2; you are storing 2 to the location pointer points to, ie, changing the value of the variable..