好的,首先我会介绍一些背景知识。 我正在开发一个涉及客户端和服务器的类项目。它们是两个独立的进程,通过我们所说的请求 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*
toRequestChannel*
当我将 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/