When I try to compile it I get a segmentation fault, and I'm pretty sure it has to do with the strcopy part of it but I can't figure out why. Any thoughts?
You haven't allocated space for the this->name, so you're copying the name into who-knows-where.
Can you use C++ strings instead? They will remove a ton of potential errors.
If you must use C strings, then you can allocate and copy the data with this->name = strdup(name); Just be sure to free the space in the destructor. And you better write a copy constructor and assignment operator (and move versions of the same).
char * tempName = new char[strlen(name) +1];
this -> name = tempName;
delete tempName;
Or would that deleting temp name deallocate the memory that name is now pointing to? I'm not very familiar with strdup so i figured i'd try a way more familiar. I have to use cstrings for this, and we can't create a copy constructor either. Also what do you mean by write an assignment operator? Overloarding the assignment operator?
> I have to use cstrings for this, and we can't create a copy constructor either.
If a user-defined copy constructor is not allowed, it is clear that dynamic allocation is not to be used.
Something like this, perhaps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct voter
{
staticconstexpr std::size_t MAX_NAME_SZ = 128 ;
char name[MAX_NAME_SZ+1] ; // +1 for an additional null character at the end
voter( constchar* name_str /* ... */ )
{
std::strncpy( name, name_str, MAX_NAME_SZ ) ; // copy at most MAX_NAME_SZ characters
name[MAX_NAME_SZ] = 0 ; // null terminate: std::strlen(name_str) could be >= MAX_NAME_SZ
// in which case std::strncpy wouldn't have terminated with a null
// ...
}
// ..
};