简体   繁体   中英

Need help using strncpy() in C++

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM