[英]Create global struct with dynamic member
I have something like the following: 我有类似以下内容:
struct t{
char arr[variable_len];
int i;
};
int main(int argc, char *argv[]){
// set size of arr to length of argv[1]
}
Is there a way to do this? 有没有办法做到这一点? I was originally just going to have arr be a pointer to an array and allocate the array separately, but this created massive issues due to the fact that I want to write this struct to a pipe (the pointer would get written and not the actual array). 我本来只是将arr用作指向数组的指针并单独分配数组,但是由于我要将此结构写入管道(因此指针将被写入而不是实际数组),这会产生大量问题)。
Setting aside the lack of error checking, you could do the following... 除了缺少错误检查外,您还可以执行以下操作...
struct t
{
int i;
int data_len;
char arr[];
};
int main( int argc, char* argv[] )
{
int data_len = atoi( argv[1] );
struct t* var;
var = malloc( sizeof( struct t ) + data_len );
var->data_len = data_len;
// open a pipe and do cool stuff to var
fwrite( var, sizeof( struct t ) + var->data_len, 1, output_pipe );
free( var );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.