简体   繁体   中英

How can I do this type conversion?

My code is here.

struct process *init_process (char *programName, int startTime, int cpuTime) {
    struct process *proc;
    proc = (malloc(sizeof(struct process)));
    if (proc == NULL) {
        printf("Fatal error: memory allocation failure.\nTerminating.\n");
        exit(1);
    }
    proc->programName = programName;
    proc->cpuTime = cpuTime;
    proc->startTime = startTime;
    proc->next = NULL;
    return(proc);
};

The compiler says that "error: invalid conversion from 'void*' to 'process*'" in line 3. I try to use process*(malloc(sizeof(struct process))) to do the type conversion but the compiler says that 'error: expected primary-expression before '*' token' this time.

Can anyone help me solve this problem?

In C++, you should use the new style casts:

    proc = static_cast<process *>(malloc(sizeof(struct process)));

But, if you really are using a C++ compiler, you should really be using new / new[] for dynamic allocation (and delete / delete[] for deallocation).

    proc = new process;

If you are porting C code to C++, and you don't want to modify the current malloc() calls, you can try adding this:

#ifdef __cplusplus
namespace cxx {
    class voidptr {
        void *p_;
    public:
        voidptr (void *p = 0) : p_(p) {}
        template <typename T>
        operator T * () const { return static_cast<T *>(p_); }
    };
    voidptr malloc (size_t sz) { return ::malloc(sz); }
    voidptr calloc (size_t cnt, size_t sz) { return ::calloc(cnt, sz); }
    voidptr realloc (void *p, size_t newsz) { return ::realloc(p, newsz); }
}
#define malloc(x) cxx::malloc(x)
#define calloc(x,y) cxx::calloc(x,y)
#define realloc(x,y) cxx::realloc(x,y)
#endif

Works for C. Works for C++.

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