static void (* __set_malloc_handler(void (*__f)()))();
I think __set_malloc_handler is a function pointer, and it points to a function which also needs a function pointer. But, I have no idea how to understand the whole statement. How does it work?
It's easier to understand with some aliasing.
//pointer to function taking no arguments and void return
typedef void(*function_pointer)();
//function taking "function_pointer" and returning "function_pointer"
function_pointer __set_malloc_handler(function_pointer __f);
To read something like that, I recommend the right-left rule. It's what I always use. There's also a spiral rule, but I get annoyed when it doesn't form a perfect spiral and I get too distracted by that to focus. You probably won't have that issue.
The explanation on either page is more thorough, but here's a crash course.
Essentially, read these symbols as:
* = "pointer to"
(...) = "function taking ..."
[...] = "array of size ..."
Read to the right until you find a ) that didn't have a matching ( yet. Then read to the left until you find a ( to match it. Start reading right again. If you hit the end of the line on the right, you finish reading to the left.
To the immediate right of the identifier __set_malloc_handler is an open parenthetical (, meaning it is a function. Everything from that to the matching ) is the parameter type. I'd recommend ignoring it at first and coming back to it later. Step by step:
__set_malloc_handler(...) //function taking ...
(*__set_malloc_handler(...)) //and returning a pointer
(*__set_malloc_handler(...))() //to a function taking no arguments
void (*__set_malloc_handler(...))() //that returns void
Looking at the parameter, we have:
(*__f) //pointer
(*__f)() //to function taking no arguments
void (*__f)() //and returning void
__set_malloc_handler is a function that takes a "function pointer to a void function" and returns a "function pointer to a void function". Keyword static makes it only visible to the current file.
Related
I'm trying to understand a Function/Method in a Library in order to port it to Java however some parameters don't make any sense to me and reading the source code the library is based on is not helping.
Function (Note the API has few comments (We can also ignore the calc handle since it's got a supplier method))
Ssr calc_ssr(CalcHandle *calc, NoteInfo *rows, size_t num_rows, float music_rate, float score_goal) {
std::vector<NoteInfo> note_info(rows, rows + num_rows);
auto skillsets = MinaSDCalc(
note_info,
music_rate,
score_goal,
reinterpret_cast<Calc*>(calc)
);
return skillset_vector_to_ssr(skillsets);
}
NoteInfo Struct
struct NoteInfo
{
unsigned int notes;
float rowTime;
};
MinaSDCalc
// Function to generate SSR rating
auto
MinaSDCalc(const std::vector<NoteInfo>& NoteInfo,
const float musicrate,
const float goal,
Calc* calc) -> std::vector<float>
{
if (NoteInfo.size() <= 1) {
return dimples_the_all_zero_output;
}
calc->ssr = true;
calc->debugmode = false;
return calc->CalcMain(NoteInfo, musicrate, min(goal, ssr_goal_cap));
}
Calc expected input file data (Only care about the #Notes: ...)
Pastebin
Question
What is NoteInfo in calc_ssr, I don't know any C or C++ so the *rows to me just seems like a pointer to a Noteinfo instance, however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me (pairing this with the fact that NoteInfo needs another parameter rowTime which I think is time of Note occurrence in the file which means that value must not be constant otherwise the produced result would be inaccurate)
Github Project: https://github.com/kangalioo/minacalc-standalone (The code alone may not explain enough but it's worth a try; best to look at API.h and discern what's used from there. Though I do warn you a lot of the Code is esoteric)
Sorry if this doesn't make much sense but I've been looking into this since June/July and this API is the closest abstraction from the bare C++ code I could find.
NoteInfo * rows here is pass by pointer. So, rows actually is a pointer to an instance of type NoteInfo. This is one of the ways to pass arrays in c++ to a function. Since arrays are contiguous in memory so we can just increment the pointer by one and get the next element of the array.
for example look at these three ways to do exactly one thing, parameter to pass an array to a function :-
1. void myFunction(int *param) {}
2. void myFunction(int param[10]) {}
3. void myFunction(int param[]) {}
Look into this link for more understanding : https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm
Also search for pass by pointer and pass by reference to look into different ways of passing arguments in c++.
2.however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me: as to this question of yours, you can now see MinaSDCalc is actually getting an array and not a single instance as passing the pointer is also one of the ways of passing an array in c++.
I have a C++ function in which I have two int's, who's purpose is to serve as counters, that are declared outside of the function in my main code. My goal is to update the counter variables with the result from the execution of the function.
I have them declared as such
int cor_letters = 0;
int cor_place = 0;
and then call my function like
res = compare(input, secret_word, &cor_letters, &cor_place);
My compare function header is:
bool compare(string user_input, string secret, int * correct_letters, int * correct_place)
and in my compare code, when I get the final values of the counters, I update them as such:
correct_letters = &cor_l;
correct_place = &cor_p;
I arrived at this solution after carefully reading through my compiler errors, and this seems to work. However, I don't quite understand why this works. In the beginning, I take the address of the two variables and pass them into the function. But the function takes two pointers. So the pointers point to the address of the passed in variables.
Up to this point I seem to grasp what's going on. But its the final assignments that I'm confused by - the pointers (note they're the var names from the function header) are then being updated to the address of the temporary inner function variables that I'm using. Why does this get me the values?
I'm more of a visual learner, and pointers are hard to grasp by just reading some text, so if you wouldn't mind making some quick text diagram to represent what's going on, that would be great. Thank you
I guess you ended up with
correct_letters = &cor_l;
correct_place = &cor_p;
in order to make the compiler stop complaining.
Your analyse about taking the address of local variable is correct.
You probably want to do this
*correct_letters = cor_l;
*correct_place = cor_p;
in order to assign the correct values to the variables
which are outside the function.
A brief memo about reference (&) and dereference (*) operations.
TYPE var_a=..., var_b=...; // some variables of a chosen type
TYPE *ptr=NULL; // a pointer on such a type, but not referencing anything yet
ptr=&var_a; // now ptr memorises the address of var_a (reference operation)
var_b=*ptr; // access the value which is stored at the address memorised
// by ptr (dereference operation) in order to read it
// (here, this has the same effect as var_b=var_a; )
*ptr=var_a+var_b; // access the value which is stored at the address memorised
// by ptr (dereference operation) in order to alter it
// (here, this has the same effect as var_a=var_a+var_b; )
I am reading The C++ Programming Language by Bjarne Stroustrup. It states an example to explain function-pointers:
int cmp1(const void∗ p, const void∗ q) // Compare name strings
{
return strcmp(static_cast<const User∗>(p)−>name,static_cast<const User∗>(q)−>name);
}
Then it uses this cmp1 in ssort, something like this:
int main()
{
cout << "Heads in alphabetical order:\n";
ssort(heads,6,sizeof(User),cmp1);
print_id(heads);
//Rest of function body
}
My question is: is &cmp1 being passed as an argument in ssort() because we can't pass a function as an argument, we can only pass a function-pointer?
My question is: is &cmp1 being passed as an argument in ssort() because we can't pass a function as an argument, we can only pass a function-pointer?
Your code does not use &cmp1. Hence, your question does not match your code.
Still, a function can be passed without using the addressof operator (&).
ssort(heads, 6, sizeof(User), &cmp1);
is the same as
ssort(heads, 6, sizeof(User), cmp1);
Functions decay to function pointers in this context.
A functions name indeed represent the starting address of the executable code for the function. So it's more like the arrays where its name can be used as pointer to the array itself. Also go through
https://www.geeksforgeeks.org/function-pointer-in-c/
I am working on a piece of structured programming homework that requires that I make a program that allows the user to enter names blah blah blah and so on. What I want to do after putting names into the string array is to print them to the screen. I had hoped to accomplish this by passing the array and the number of names contained therein to a function that would then print them to the screen. I wanted to pass the array and number of names as constants so that it would safeguard them so they couldn't be modified by the function, just read-only. I don't understand why I can't put const before the string array or the number of names though.
void writeNames (const string namelist[], const int number_of_names)
Is this something I just have to accept or is there a way I can pass both of those as read-only to the function? I can complete the homework without this so this is more a question of curiousity than a "help me with my homework" one.
P.S. Vectors seem to be a way of doing a lot more things with strings and such, but we haven't got to them in class yet and therefore I can't use them yet either.
Thanks
Without seeing what you're doing within the function, it's hard to answer the question, but my crystal ball says that you're probably doing something that could potentially modify one of the parameters within your method, so the compiler is complaining because you declared the parameter const.
As an example, something like this works just fine:
void writeNames(const std::string namelist[], const int number_of_names)
{
for(int i = 0; i < number_of_names; i++) {
std::cout << namelist[i] << std::endl;
}
}
However, something like this would cause a compiler error, since you're changing one of the variables:
void writeNames(const std::string namelist[], const int number_of_names)
{
while(number_of_names--) { // <-- We're modifying a const value here
std::cout << namelist[count] << std::endl;
}
}
Incidentally, putting the const modifier on your "number_of_names" parameter is somewhat redundant since you're passing the parameter by value, so changing the value within the function would have no effect on the value of the input parameter in the calling function. A change in any of the strings in the array, however, would be reflected in the calling function, so the const modifier there makes sense. Generally you would use const only on parameters that are either pointers, or being passed in by reference.
I'm building a comparator for an assignment, and I'm pulling my hair out because this seems to simple, but I can't figure it out.
This function is giving me trouble:
int compare(Word *a, Word *b)
{
string *aTerm = a->getString();
string *bTerm = b->getString();
return aTerm->compare(bTerm);
}
Word::getString returns a string*
Error:
In member function `virtual int CompWordByAlpha::compare(Word*, Word*)':
no matching function for call to...
...followed by a bunch of function definitions.
Any help?
You're comparing a string to a string pointer, and that's not valid. You want
return aTerm->compare(*bTerm);
You aren't getting the different uses of the * operator. The use of the * in "string* bTerm = b->getString()" means "bTerm is a pointer to a string". The use of the * inside of compare(*bTerm) means "take the value of the location pointed to by bTerm" instead of just using compare(bTerm) which simply attempts to compare the value of bTerm itself, which is a hex address.
This is also happening on the left side of that call:
aTerm->compare(*bTerm); //this statement
(*aTerm).compare(*bTerm); //is the same as this statement
The -> operator just reduces the amount of typing required.
P.S.: This kind of stuff you could have easily figured out from Google or your programming textbook. Although others may disagree, I don't feel that questions about completely basic syntax have any place on Stack Overflow.