I've been trying to use arrays in a class constructor. Here is my code:
struct Motor_Group{
int Motors[3];
int Encoder;
};
int main()
{
Motor_Group Left_Drive {{2,3},3};
Motor_Group Right_Drive {{2,3},3};
cout<< sizeof(Left_Drive.Motors)/sizeof(int);
return 0;
}
But, the problem is that i want to make the length of the array motors to be undefined untill its contents is declared. How can i do that?
Thanks for your kind help!
If you do not need MotorGroups to be of the same type,
then you could template the array size.
Using std::array
#include <array>
#include <iostream>
template<size_t motor_count>
struct Motor_Group{
std::array<int,motor_count> Motors;
int Encoder;
};
int main()
{
Motor_Group<2> Left_Drive {{2,3},3};
Motor_Group<3> Right_Drive {{2,3,4},3};
std::cout<< Left_Drive.size();
// Left_Drive = Right_Drive; // Error at compile time, since Motor_Group<2> != Motor_Group<3>
return 0;
}
I have a C++ code below which create an array of pointers to a struct
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define WATCH(x) std::cout << #x << ": " << x << std::endl;
typedef struct
{
double thickness;
char name[80];
virtual double getDensity() const {return 0.1;}
} mat_prop_t;
struct mat_el_prop : public mat_prop_t
{
double density;
double young;
double poisson;
virtual double getDensity() const {return density;}
};
int main(int argc, char** argv)
{
mat_prop_t** mat_prop;
mat_prop = (mat_prop_t**) calloc(1, sizeof(mat_prop_t*));
mat_prop[0] = (mat_prop_t*) calloc(1, sizeof(mat_el_prop));
mat_el_prop* mat1 = (mat_el_prop*) mat_prop[0];
mat1->density = 2.038735;
mat1->young = 2.0;
mat1->poisson = 0.3;
mat1->thickness = 1.0;
WATCH(mat1->density)
WATCH(mat1->getDensity())
free(mat_prop[0]);
free(mat_prop);
return 0;
}
I think the construct is correct, but it gives a seg fault error at line
WATCH(mat1->getDensity())
However, when the virtual keyword is removed, the code runs fine. Could anybody help to explain to me why?
calloc() can only be used to allocate space for primitive types and POD structures. Since your struct has a virtual function, it's not POD, so you need to use new to ensure that the vtable is created properly.
mat_prop_t **mat_prop = new mat_prop_t*[1];
mat_prop[0] = new mat_el_prop;
mat_el_prop *mat1 = mat_prop[0];
You could technically use calloc() for mat_prop, since it's an array of pointers. But in C++ you should generally use new, not the C memory allocation functions.
Getting segmentation fault while trying to print content member using pointer l_pContent in below program.
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
struct responseStruct *l_pContent = (struct responseStruct*)l_httpResponse;
cout << l_pContent->content << endl; // Error : Segmentation Fault
return 0;
}
The variable content is a pointer to an unsigned char and so is l_httpResponse. You can therefore create an instance of the responseStruct and then assign the instance's content pointer to l_httpResponse.
Here is an example:
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
// Create instance of an responseStruct struct
responseStruct rs;
// Make content point to the start of l_httpResponse
rs.content = l_httpResponse;
// Test for access without segfault
cout << static_cast<unsigned>(rs.content[1]) << endl;
return 0;
}
Or here is a live demo.
Omitting the fact that the idea of such code is mysterious to me, here is what causes the error:
If we assume that members of the responseStruct will match ideally the data from the l_httpResponse, that sizeof(int) and sizeof(unsigned char *) are 4, that your architecture uses little-endian notation, and that your compiler uses ASCII (which it probably does), you end with:
Handle == 0x04030201
headerLen == 0x08070605
bodyLen == 0x02010009
content == 0x64636261
Now, content is a pointer, so 0x64636261 is an address in your memory. It doesn't point to your "abcde..." string. It's made up of it's first four bytes. And points at some non existing region. That's why you end up with segmentation fault.
I have structs templated by int derived from a Base struct.
struct Base { int i; double d; };
template< int N > struct Derv : base { static const int mN = N; };
I need to make an array of Derv< N > where N can vary for each struct in that array. I know C/C++ does not allow arrays of objects of different types, but is there a way around this? I was thinking of separating the type information somehow (hints like pointers to Base struct or usage of union spring to my mind, but with all of these I don't know how to store the type information of each array element for usage DURING COMPILE TIME). As you can see, the memory pattern of each Derv< N > is the same.
I need to access the type of each array element for template specialization later in my code. The general aim of this all is to have a compile-time dispatch mechanism without the need to do a runtime "type switch" somewhere in the code.
It is most certainly impossible. If you did
int i;
std::cin >> i;
some_magic_array X[size];
Then what is the type of X[i]? Oh, wait, you can't possibly know. It's nothing C++ specific, it's fundamentally impossible. That's why no some_magic_array will ever exist that permits this.
Unless you effectively use a std::tuple and guarantee that i is constexpr. Then you absolutely can do this with std::get<i>(tup);.
I guess you can use ptr = dynamic_cast<Type>(element); .. ptr will equal to NULL if it's the wrong type.
For example:
#include <map>
#include <cmath>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
struct Base { int i; double d; Base(){}; virtual ~Base(){};};
template< int N > struct Derv : public Base { static const int mN = N; ~Derv(){}; };
int main(int argc, char **argv){
Base* arr[2];
arr[0] = new Derv<10>;
arr[1] = new Derv<5>;
Derv<10> *ptr = dynamic_cast<Derv<10>* >(arr[0]);
Derv<5> *ptr2 = dynamic_cast<Derv<5>* >(arr[0]);
cout << ptr << endl << ptr2 << endl;
return 0;
}
// That should print
0x9571008 //ptr to object will differ every time.
0 // Null because of wrong type.
But you'll need to define virtual destructor in your struct for this to work, and/or a virtual function.
I am getting the above error during compilation:
Structure:
struct connection_handlers
{
int m_fd;
}
struct connection_handlers ** _queue;
int main()
{
_queue = (struct connection_handlers **) malloc ( 3* sizeof ( struct connection_handlers *)); //Allocating space for 3 struct pointers
for (i=0;i<3;i++)
{
_queue[i]->m_fd=-1;
}//Initializing to -1
//.....
//I assign this varaible to the file descriptor returned by accept and then
//at some point of time i try to check the same variable and it gives compilatio error.
for (i=0;i<3;i++)
{
if (_queue[i]->m_fd!=-1)
}//It give error at this line.
}
What could be the reason for error.
Thanks
Since you tagged this question both C and C++, here is what is wrong with your C++.
don't put struct inside your casts
don't use implicit int for your loop counters
struct declarations need a terminating ;
_queue is declared with a messed-up type
your last loop is missing
Once you clean that up it compiles fine.
#include <cstdlib>
struct connection_handlers {
int m_fd;
};
int main() {
connection_handlers** _queue = (connection_handlers**) malloc(3*sizeof (connection_handlers*));
for (int i=0;i<3;i++) {
_queue[i]->m_fd=-1;
}
for (int i=0;i<3;i++) {
if (_queue[i]->m_fd!=-1)
; // DOES NOTHING
}
}
_queue[i] is a connection_handlers *. You can't compare that to -1, which is an int. Did you mean to check _queue[i]->m_fd?