Reputation: 13
I am stuck for hours during my assignment. Specifically, on this part:
The constructor should take a const-qualified C-Style string as its argument. Use the
strncpy()
function from the<cstring>
library to copy it into the underlying storage. Be sure to manually null-terminate the attribute after you copy to assure that it is a valid C-String (in case the parameter contained a much larger string).
Where am I making mistakes, and how should I change my code?
#ifndef STRINGWRAPPER_H
#define STRINGWRAPPER_H
class StringWrapper{
public:
StringWrapper (const char myString);
const static int max_capacity = 262144;
private:
int size = 1;
char myString [40];
};
#endif
#include "StringWrapper.h"
#include <cstring>
StringWrapper::StringWrapper (const char myString){
strncpy(StringWrapper::myString, myString, sizeof(myString));
}
#include <iostream>
#include "ThinArrayWrapper.h"
#include "ArrayWrapper.h"
#include "StringWrapper.h"
#include <stdexcept>
int main(){
char myString[]{ "string" };
StringWrapper StringWrapper('h');
return 0;
}
Upvotes: 0
Views: 562
Reputation: 852
First of all, your call to strncpy
is wrong. Please check the reference regarding the strncpy
from here.
According to the definition of strncpy
:
char *strncpy(char *dest, const char *src, std::size_t count);
In your case, you are calling strncpy
like this:
strncpy(StringWrapper::myString, myString, sizeof(myString));
Here, myString
is a const char
type variable. You need to make it to const char *
. If you like, you can check my modification of your code from here.
Upvotes: 3