c - 在运行时声明和初始化 C 中的类数组

标签 c arrays class unix malloc

好的,首先我会介绍一些背景知识。 我正在开发一个涉及客户端和服务器的类项目。它们是两个独立的进程,通过我们所说的请求 channel 相互通信。

客户端收集请求数量的命令行参数、请求 channel 的缓冲区大小以及发送请求的工作线程数量(分别为 -n、-b 和 -w)。

用户需要多少个工作线程,我就必须在客户端和服务器之间创建多少个请求 channel 。

RequestChannel *channel;

int main(int argc, char * argv[])
{
    char *n=NULL, *b=NULL, *w=NULL;
    int num, buf, workers;
    char optchar=0;

    while((optchar=getopt(argc,argv,"n:b:w:"))!=-1)
    switch(optchar)
    {
        case 'n':
            n=optarg;
            break;
        case 'b':
            b=optarg;
            break;
        case 'w':
            w=optarg;
            break;
        case '?':
            break;
        default:
            abort();
    }
    num=atoi(n);
    buf=atoi(b);
    workers=atoi(w);

    channel=malloc(workers*sizeof(RequestChannel));

    cout << "CLIENT STARTED:" << endl;

    pid_t child_pid;
    child_pid = fork();

    if(child_pid==0)
    {
       execv("dataserver", argv);
    }
    else
    {
        cout << "Establishing control channel... " << flush;
        RequestChannel chan("control", RequestChannel::CLIENT_SIDE);
        cout << "done." << endl;

        for(int i=0;i<workers;i++)
            RequestChannel channel[i](chan.send_request("newthread"), RequestChannel::CLIENT_SIDE);
    }
}

我在 malloc 行中遇到编译错误,但我不知道问题是什么。我只是希望能够像 channel[i] 一样访问每个 RequestChannel

现在的情况是,我收到一条错误消息

invalid conversion from void* to RequestChannel*

当我将 sizeof(RequestChannel) 替换为 sizeof(*RequestChannel) 时,我收到一条错误消息

expected primary-expression before ')' token.

最佳答案

malloc 行是正确的(但请检查它是否返回 NULL)。 C++ 编译器(不是 C)会提示,因为在 C++ 中你需要强制转换:

channel = static_cast<RequestChannel *>malloc(...);

或者,使用 C 语法:

channel = (RequestChannel*) malloc(...);

关于c - 在运行时声明和初始化 C 中的类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596876/

相关文章:

与 OR (|) 运算符混淆

c# - 最长排序子序列的长度

c# - Inspector 中的 Unity3d 二维数组

javascript - 无法通过在 javascript 中识别对象的父 ID 将对象插入父数组

c++ - 通过引用错误的 C++ 传递字符串

JavaScript "classes"

c++ - DirectInput 未解析的外部符号

c++ - C/C++中原始指针和函数指针支持的操作有哪些?

c++ - 在 C++ 类中初始化数组

c - 在 Xcode 中构建旧的 unix C 项目时指针给出错误?