Initialize a variable in c++ [closed] - c++

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 months ago.
Improve this question
So I want to initialize a variable with a value like this:
ADM_job_t job{42};
The structure of ADM_job_t is this one:
typedef struct adm_job* ADM_job_t;
And adm_job looks like this:
struct adm_job {
uint64_t id;
};
So my idea was to intialize my variable with an int, because is the "final" type, but I'm getting an error saying that I can not initialize an adm_job with an int. I can not change the structure that has been provided. How can I do it?
Thank you!

As mentioned in the comments you do actually have to create a adm_job object.
Here is one way
adm_job obj{42};
ADM_job_t job = &obj;

Even if you can't change the adm_job structure, you can probably still ignore ADM_job_t for object creation, and use smart pointers instead. I recommend starting with something like this:
#include <memory>
struct adm_job {
uint64_t id;
};
typedef struct adm_job* ADM_job_t;
void foo(ADM_job_t p) {
}
int main () {
//auto job = std::make_unique<adm_job>(42); // C++20
auto job = std::unique_ptr<adm_job>{new adm_job{42}}; // C++11
foo(job.get());
}
job's type is std::unique_ptr<adm_job>. As you can see, you can still pass the result of job.get() to any old C function that makes non-owning use of ADM_job_t.
You needn't worry about deleting the object like this.
Read about unique_ptr. There are some other types of smart pointer depending on who else is going to "own" the pointed two object during its lifetime.

Related

coping an array from one object to another object [closed]

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 2 years ago.
Improve this question
set &set::operator=(set const &s) {
elems = new int[s.num_elems];
num_elems = *(new size_t);
for (size_t i = 0; i < s.num_elems; i++) {//i am getting error in this line on "=" saying " a value type int* cannot be assigned tpo an entity of type int".
elems[i] = &(s.elems[i]);
}
num_elems = s.num_elems;
return *this;
};
i am trying to copy an object to another object they each has two private size_t num_elems and int *elems.i have tried changing the pointer symbols and copying the array directly but it gives me error everytime
This line is bad: num_elems = *(new size_t);
It just leaks a few bytes and does nothing useful. Delete it.
Then there is a problem where you are assigning the address of s.elems[i] into elems[i]. Which is not right because elems[i] is an integer, and the address of s.elems[i] is... well, an address.
So you need to change this line: elems[i] = &(s.elems[i]); to this: elems[i] = s.elems[i];
A few tips:
& this is called the "address of" operator. It gets the address of where something is in memory.
* this is called the "pointer dereference" operator. It helps you access what the pointer is pointing at.
When you access an array with square brackets, like this: elems[i] you're de-referencing it. Which means you're using the value that the pointer is pointing at. It's the same as doing this: *(elems + i)
Study your pointers :D They're a little tricky at first but they get easier with time and practice.

can't declare method in class (c++_ [closed]

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 4 years ago.
Improve this question
In my header file I declare structure
typedef struct _PreprocessedImage
{
cv::Rect straight;
cv::Rect diagonal;
bool empty = true;
...
...
} PreprocessedImage;
Then I create class with method
std::vector<float> processData(cv::Mat &image, bool drawRegions = false, PreprocessedImage &preproc);
.
Try to compile and got
"error: default argument missing for parameter 3"
But when I try to declare method with default value, like that:
std::vector<float> processData(cv::Mat &image, bool drawRegions = false, PreprocessedImage &preproc = PreprocessedImage());
.
I got
"error: invalid initialization of non-const reference of type
'PreprocessedImage& {aka _PreprocessedImage&}' from an rvalue of type
'PreprocessedImage {aka _PreprocessedImage}'"
How can i fix it?
All parameters with defaults should be at the end of the list, so you need something like:
std::vector<float> processData(cv::Mat &image, PreprocessedImage &preproc, bool drawRegions = false);
.
To add to paxdiablo's answer.
Yes, the default-argument parameters must come last. Your attempt to work around this by also giving preproc a default argument failed because a temporary cannot bind to an lvalue reference (it would have to be const); besides, giving something a default "for the sake of it" is probably not what you wanted to do.
An alternative, that doesn't require re-arranging your existing function, is to write a forwarding overload instead of using default arguments:
std::vector<float> processData(cv::Mat& image, bool drawRegions, PreprocessedImage& preproc)
{
/* ... */
}
std::vector<float> processData(cv::Mat& image, PreprocessedImage& preproc)
{
return processData(image, false, preproc);
}
By the way, you don't need (or want) that antique C-style typedef struct A { ... } B syntax in C++ (unless you require direct C compatibility); you just want struct B. And, if you really must go for the former, you should pick a name that isn't reserved to the implementation.

How to dereference an array element (C++) [closed]

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 8 years ago.
Improve this question
I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.
int size = 5;
string* myArray = new string[size];
I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?
string line;
myArray[0] = "Hello";
line = *myArray[0];
Edit:
I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.
void MyClass::setLine(string line)
{
myLine = line; /*This is a private variable in MyClass*/
}
///////////////
MyClass* elements = new MyClass[size];
elements[0].setLine(myArray[0]);
I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.
If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.
Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.
As such, no extra dereference is needed. Just drop the asterisk in the failing line.
Valid code will look like
string line;
myArray[0] = "Hello";
line = myArray[0];
By the way you could use class std::vector instead of the array if you are going to add or remove elements from the collection.
For example
std::vector<std::string> myArray;
myArrray.reserve( 5 );
myArray.push_back( "Hello" );
line = myArray[0];

Use pointers to create a class member [closed]

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 8 years ago.
Improve this question
I am really confused about pointers. Read some articles about them and thought i got them, but i seems i didn't. I want to create a Team "Team1" which i normally would create by Team Team1; I have the name Team1 already stored as a string from an reading input of a textfile and thought i could create this team by pointers.
#include <iostream>
#include <string>
#include <vector>
class Team
{
private:
std::string m_teamname;
};
int main()
{
std::string wort = "team1";
std::string* pointer;
pointer = &wort;
std::string wort2 = *pointer;
std::cout << wort2;
Team *pointer;
std::cin.get();
}
I got the error C2371: 'pointer' : redefinition; different basic type " which is quite selfexplaning but still i dont get why it does not work as *pointer shows to the adress where the string "team1" is stored. Is there a way to do it ?
This has nothing to do with pointers, per se. You are defining the same variable twice with different types (as the error says: "pointer: redefinition").
std::string* pointer;
...
Team *pointer;
You define a variable named pointer with type std::string*, but then you try and define another variable with the same name. You'll have to rename one of them to something else.
You'd run into the same problem with any type:
int x;
double x; // <- error: there's already an x

Passing a LPDWORD as out parameter [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am new to C++ and I need to create a function with this structure:
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
DWORD myDword = 1;
myLpdword = &myDword;
return true;
}
int main(){
DWORD outDword = 20;
myfunc(&outDword);
cout << outDword << end1;
return 0;
}
I expected that the value of outDword would be 1 (changed by myfunc), but the value is not changed by myfunc.
Please, can you give me a hint to solve this problem?
Like this
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
*myLpdword = 1;
return true;
}
Out parameter is not something that means anything in C++. MS use it but only because they are using a consistent terminology across different languages.
In C++ terms what you did is pass a pointer to the variable you want to modify to myfunc. What the above code does is take that pointer and dereference with the * operator it to modify the variable you wanted modified.
I like that you're writing small test programs to check your understanding of C++. But as others said there's no real substitute for a decent book. Any C++ book is going to cover this.
You passed in a pointer to outDword.
myLpdword is now a pointer to outDword.
You then changed myLpdword to be a pointer to myDword.
You never did anything with the VALUE of outDword.
You assigned the pointer of a variable that will not exist after exiting the function body (read on scopes in C/C++.
To solve your problem, assign the value of the variable to the dereferenced pointer, like so: *myLpdword = myDword;. It would also be wise to check that the value of the pointer is not null before dereferencing it like this: if (myLpdword == 0) { return; } . This check doesn't guarantee that the pointer is safe to assign to, but Atleast guards you against null pointer access.
In C++ this is called pass-by-reference. You denote it with an ampersand in the function signature:
bool myfunc(DWORD &myDword) {…
The ampersands you are using now are actually getting the address of the variables, so you should remove those.